I want to use the react-query library, but this library is only usable in functional components. I currently have a class component which dynamically sets the state of fields, based on a string. Eg (simplified, in reality it gets the fields from a REST-call which results in different fields every time, that's why it needs to be dynamic):
class MyComponent extends React.Component {
constructor() {
super();
this.primaryFields = ["username"];
this.uiFields = ["first_name", "last_name", "email"];
this.state = {}
this.primaryFields.map(x => {
this.state[x] = "no key given";
})
this.uiFields.map(x => {
this.state[x] = "";
})
}
...
...
}
But since hooks can't be used in a loop, nested functions or in callback functions, i don't have a way of dynamically setting the state with:
useState()
Is there a way to dynamically set state with hooks in functional components in a same way i do that in my class components?
updateState(state => { state[fieldName] = value })thansetState(state => ({ ...state, [fieldName]: value })). Especially when you deal with arrays and nested objects. Let the library deal with the problem of mutations.