Set the React.FC state with values from a Promise in typescript

Viewed 972

Im new in react, and i want to assign an array of objects to a React.FC state. My api logic looks like this:

class LandApi {
    async getLands(): Promise<Land[]> {
        const response = await fetch('http://localhost:8080/api/lands', {
           method: 'GET',
           headers: { 'Content-Type': 'application/json' }
        });

        return response.json();
    }
}

And i have this functional component:

 const MapLands: React.FC  = () =>
{
let [state, setState] = useState([])

useEffect(() => {
    LandApi.getLands().then((data) => {
        setState({
            landList: data  //the problem is here
        })
    })
})

return (
    <div>
        {
            //Map logic here
        }
    </div>
)
}

How can I 'put' that Land[] array in the functional components state, so i can map it later?

I'm pretty new to web programing as you can probably tell.

With sincere thanks,

Samuel

1 Answers

Assuming the JSON API is returning an array, then you almost had it!

First, add a type to your state, because typescript can't know what's in an empty array declared as [].

let [state, setState] = useState<Land[]>([])

And then pass your result directly to setState(), with no object in between:

LandApi.getLands().then((data) => {
  setState(data)
})

Or more succinctly:

LandApi.getLands().then(setState)

This works because it's the same signature as the inline function that was there before. It takes one argument that is the new value.

Related