#Best practice for fetching data and the transfer data to signals that I can can them in the input fi

9 messages · Page 1 of 1 (latest)

twilit ginkgo
#

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;

#

Am I right to do this?

wide widget
# twilit ginkgo 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

const updateName = action(async (id: string, name: string) => {
     return fetch(`https://api.example.com/user/${user().id}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name: newName() }),
    }).then((resp) => resp.json()) 
  },
  {
    name: "user.update-name",
    onComplete(submission) {
      // Do something with action result like toasting message if needed
      // Or calling refetch if receive success in submission.result
    }
  }
)
#

for data fetching, with simple use case, you can refer to createResouce or createAsync from the router

twilit ginkgo
#

If I want to save the data requested by createResource in a global store, what should I do