Home > Software design >  ReactJS - How can I refer a state using computed values?
ReactJS - How can I refer a state using computed values?

Time:01-03

Been trying to find a solution here but it seems tricky.

I have these states:

const [items, setItems] = useState([{ id: uuidv4(), text: 'Your items goes here' }]);
const [snippets, setSnippets] = useState([{ id: uuidv4(), text: 'Your snippets goes here' }]);
const [keywords, setKeywords] = useState([{ id: uuidv4(), text: 'Your keywords goes here' }]);
const [urls, setUrls] = useState([{ id: uuidv4(), text: 'Your URLs goes here' }]);
const [currentState, setCurrentState] = useState("items")

And I'm using this code to render it into the page:

{items.map((i, index) =>
     <SingleItem
          key={i.id}
          text={i.text}
     />
 )}

I want to be able to switch between states dynamically, but when I try this it doesn't show the right state and I get empty list:

{[currentState].map((i, index) =>
               <SingleItem
                    onBlur={handleBlur}
                    key={i.id}
                    text={i.text}
               />
)}

Is there a way to use computed values as a reference to another state? am I missing something? should I use other way to achieve it?

I'm using functions and not classes. Also I don't use redux or context.

Thanks in advance.

CodePudding user response:

You should define a map between the name and the state values.

const [items, setItems] = useState(...);
const [snippets, setSnippets] = useState(...);
const [keywords, setKeywords] = useState(...);
const [urls, setUrls] = useState(...);

const stateMap = {items, snippets, keywords, urls};
const [currentState, setCurrentState] = useState("items");

and then use

stateMap[currentState].map((i, index) =>
   ...
);

CodePudding user response:

You can use a render function to decide what items to show. Something like this:

   const renderItemsByType = (type = "items") => {
  let stateToUse = items;
  switch (type) {
    default:
    case "items":
      stateToUse = items;
    case "snippets":
      stateToUse = snippets;
    case "keywords":
      stateToUse = keywords;
    case "urls":
      stateToUse = urls;
  }

  return stateToUse.map((i, index) => (
    <SingleItem onBlur={handleBlur} key={i.id} text={i.text} />
  ));
};
  • Related