Bobby
Bobby

Reputation: 37

How do I save a previous state in react?

With each onClick I am rendering a new react component. In each component I am submitting a different text value. Problem I am having is that when i type in a new text and click the button the newState is set but it updates all rendered components. So I was wondering if there was a way for me use previous states in react. Also the way I thought about handling this issue was by pushing each new state in an array, but it didn't work. What happened was the array would simply be updated with the new value. So how can I solve this issue. Examples would greatly be appreciated.

Upvotes: 0

Views: 841

Answers (2)

Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

You are right, you need to use an array as state and update it but probably you were not doing it right. Try this:

const ParentComponent = () => {
const [itemsArray, setItemsArray] = useState([])

// Pass this method and use it in the child component
changeItem = (index, key, val) => {
    const newArray = [ ...itemsArray ];
    newArray[index][key] = val;
    setItemsArray(newArray);
}

return (
    <>
        {
            itemsArray && 0 < itemsArray.length &&
                itemsArray.map((item, key) => <Component changeItem={changeItem}/>)
        }
    </>

} }

Upvotes: 1

Barry Michael Doyle
Barry Michael Doyle

Reputation: 10658

The problem you have is that you are linking all the components to the same state key.

What you actually need to do is have a state with multiple keys to hold the value for each component.

So here's an example using useState.

const ParentComponent = () => {
  const [state, setState] = useState({ val1: '', val2: '' })

  return (
    <>
      <Component1 value={val1} onChange={(value) => setState({ ...state, val1: value })} />
      <Component2 value={val2} onChange={(value) => setState({ ...state, val2: value })} />
    </>

  }
}

By the sounds of things you probably have an array, that gets updates, you so could adapt this concept to work for you.

It's tough to give you a great example without seeing your implementation. I can update mine to help you if you provide more information.

Upvotes: 1

Related Questions