hannah
hannah

Reputation: 195

API call using React Hooks

I am trying to fetch an api with react hooks. I am able to get the data from the api and declared some attributes with useState. Now I am trying to set the attributes from the api to the attributes in useState, the same way you would do it with setState in class components, but I am not sure how to go about it.

enter image description here

enter image description here

Above is the userData that I did a console.log for in the promise.

Upvotes: 1

Views: 218

Answers (2)

Murillo Ferreira
Murillo Ferreira

Reputation: 1433

useState returns an array where the first element is the data and the second is a function which you call anywhere to update the state later.

From your example:

    // Receive the array from useState and use the "array destructuring"
    const [myState, setMyState] = useState({/*... you data */});

    // ...
    useEffect(() => {
        // fetch...
        // .then...
        .then(userData => {
            console.log(userData);
            setMyState(userData); // call the function here
        });
    // ...

This should be enough to have your state object updated!

Upvotes: 1

jean182
jean182

Reputation: 3505

You need to make a few changes, first is that the initial state should be an array

const [initialState, setInitialState] = useState([])

I would use an array since the response is giving you an array of users, in your then statement where you have the console.log you can do

setInitialState(userData)

That will update the initialState value with the array of items, if you actually plan to use just one user just pick one from the userData array. The setInitialState will be the function you need to use when you plan to use the initialState value.

Upvotes: 0

Related Questions