skip to Main Content

Let say I have a useState to store a user object:

const [user, setUser] = useState({
   name: "",
   age: "",
   type: ""
})

and a select box to show the type

<select
   className="input"
   value={user.type}
   onChange={handleType}

>
   <option value='A'>A</option>
   <option value='B'>B</option>
</select>

I want to call a api to get the user data and the selected option will change to user.type

useEffect(() => {
    axios
      .get("https://api.test.com/users/1", {})
      .then((res) => {
        console.log(res);
        setUser(res.data.user);
      })
      .catch((err) => console.log(err));
  }, []);

However, the selected option does not change.

2

Answers


  1. You can spread the response like this

    useEffect(() => {
        axios
          .get("https://api.test.com/users/1", {})
          .then((res) => {
            console.log(res);
            setUser(prev => ({...prev, ...res.data.user}));
          })
          .catch((err) => console.log(err));
      }, []);
    
    Login or Signup to reply.
  2. I hope my example could help you. if you update data to the value of select, updated data is not included in the options list. the select value will not update.

    • so, when you update the value of select, after the API call.
    • update option-list either.

    example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search