0

Here is the state:

const [state, setState] = useState({
    menuCatalog: true,
    menuCommon: true,
    fetched_data: []
});

This is an example of fetched data I try to set to the state property "fetched_data":

[{"id": 1, "name": "some_name", "ip": "127.0.0.1", "port": 5353}, {"id": 2, "name": "some_name", "ip": "128.0.0.1", "port": 5353}]

This is how I try to set it:

const fetched_stuff = await fetchStuff();

const fetched_data = fetched_stuff["data"];

setState({
    fetched_data
});

And this is error I get:

Argument of type '{ fetched_data: any; }' is not assignable to parameter of type 'SetStateAction<{ menuCatalog: boolean; menuCommon: boolean; fetched_data: never[]; }>'.
Type '{ fetched_data: any; }' is missing the following properties from type '{ menuCatalog: boolean; menuCommon: boolean; fetched_data: never[]; }': menuCatalog, menuCommon  TS2345

Tried a dozen different things, no solutions online help. How to actually set the array of objects to the state in typescript.react?

3
  • What about setState({menuCatalog: true,menuCommon: true,fetched_data});? Commented Nov 9, 2020 at 13:25
  • @yudhiesh I think it should be setState(prev => ({...prev, fetched_data})). It's possible that the booleans may not always be true. Commented Nov 9, 2020 at 13:31
  • @yudhiesh What about setState({menuCatalog: true,menuCommon: true,fetched_data});? Ofc. I tried that, and it says this: Argument of type '{ stations_info: any; }' is not assignable to parameter of type 'SetStateAction<{ menuCatalog: boolean; menuCommon: boolean; stations_info: never[]; }>'. Commented Nov 10, 2020 at 4:14

1 Answer 1

2

You should overwrite the previous state using functional updates. Your default state was

{
    menuCatalog: true,
    menuCommon: true,
    fetched_data: []
}

However, when you later updated it, you only passed in fetched_data, which TypeScript recognized as an error because the original state also expects a menuCatalog and menuCommon property. What you should do be doing instead is that when updating the state, just use the functional update where properties of the previous state is passed, while the property you want to update is added at the end. This ensures your new state still has the old properties as well as the new property.

setState(prev => ({
  ...prev,
  fetched_data
}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.