Best practice for fetching data and the transfer data to signals that I can can them in the input fi
import { createSignal, createEffect } from "solid-js";
function UserProfile() {
const [user, setUser] = createSignal({ name: "", id: "" });
const [newName, setNewName] = createSignal("");
// Fetch user data when the component mounts
createEffect(() => {
fetch("https://api.example.com/user/1") // Replace with your API endpoint
.then((response) => response.json())
.then((data) => {
setUser(data);
setNewName(data.name); // Initialize the input with the fetched name
});
});
const handleSave = () => {
// Save the updated name
fetch(
https://api.example.com/user/${user().id}
, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: newName() }),
})
.then((response) => response.json())
.then((data) => {
setUser(data); // Update the user state with the new data
})
.catch((error) => {
console.error("Error updating user:", error);
});
};
return (
<div>
<h1>User Profile</h1>
<p>User ID: {user().id}</p>
<label>
Name:
<input
type="text"
value={newName()}
onInput={(e) => setNewName(e.target.value)}
/>
</label>
<button onClick={handleSave}>Save</button>
</div>
);
}
export default UserProfile;4 Replies
Am I right to do this?
you can make use of solid-router to handle the action for you
https://docs.solidjs.com/solid-router/reference/data-apis/action
for example
for data fetching, with simple use case, you can refer to
createResouce
or createAsync
from the router
https://docs.solidjs.com/reference/basic-reactivity/create-resource
https://docs.solidjs.com/solid-router/reference/data-apis/create-asyncIf I want to save the data requested by createResource in a global store, what should I do
There's an experimental option for
storage
https://docs.solidjs.com/reference/basic-reactivity/create-resource#options
But if you tend to fetch only once and never revalidate, then consider using a simple store and a createComputed
to fetch and write to the initial store