Jagger
Jagger
SSolidJS
Created by Jagger on 12/1/2024 in #support
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;
10 replies