1

I have a series of toggle buttons which toggle between values 'pending' and 'active'. When onChange, I make a post request to update the value of the element that was toggled in the database. However, I want to be able to change the value of the element to its new value once toggled, locally.

I know I can use useState hooks, but the issue is that there can be potentially 100s of these elements, so I think that's out of question. Is there some other way I can update the value of the element?

This is what I'm currently working with

  const toggleChange = async (e) => {
    let elemId = e.target.id;
    let newStatus; 
    if (e.target.value === 'pending') {
      newStatus = 'active';
    } else if (e.target.value === 'active') {
      newStatus = 'pending';
    }
     
    // post request
    await updateStatus(elemId, newStatus);
  };



 return (
 ...
 <Switch
 onChange={(e) => {
     toggleChange(e);
  }}
  defaultChecked={status == 'active' ? true : false}
  id={elem_id}
  value={status}
 />
 )
2
  • Each <Switch> should manage its own state, then you won't have 100s of useState, but only one. Commented Jan 7, 2022 at 14:50
  • The issue is that <Switch> is actually a ChakraUI component that I'm using. However, I do think I can solve that issue by creating my own switch component using that. Thank you for your reply. I guess I might use this as a last resort. Commented Jan 8, 2022 at 3:02

1 Answer 1

1

You can try to use useReducer instead of useState

https://reactjs.org/docs/hooks-reference.html#usereducer

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

2 Comments

Is there another way without the use of Reducers? Because I'm actually using NextJS
theres no problem in using useReducer in NextJS, this is part of react, its not based on Redux... its just solution for "more complex state of component" not "whole app store"

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.