1

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?

1
  • You might want to take a look at immerjs and its hook useImmer. For this example it may be overkill to add a library, but as your state changes get more complex, it may be simpler to write updateState(state => { state[fieldName] = value }) than setState(state => ({ ...state, [fieldName]: value })). Especially when you deal with arrays and nested objects. Let the library deal with the problem of mutations. Commented Mar 6, 2021 at 21:04

1 Answer 1

1

I don't see what this has to do with react-query, but you can also just make one useState object that holds your value:

uiFields = ["first_name", "last_name", "email"]
const [state, setState] = React.useState(() => uiFields.reduce(acc => {
    acc[v] = "no key given" 
    return acc
}, {}))

const updateState = (fieldName, value) =>
    setState(previousState => ({ ...previousState, [fieldName]: value })

This is a bit more convoluted, because you need to always return the full object when calling setState, as opposed to the class based version, where you can return a partial object.

But now you can call updateState("myKey", "myValue") and it should work like the class-based equivalent.

For more complex state management, there is also useReducer, which might come in handy here.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, this is what i was looking for. My app now dynamically creates a whole list of form-fields which i can couple to a dynamically generated state.

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.