1

Editing for clarification that this is around a hook as this was marked as a duplicate even though the other question doesn’t use hooks. Another comment had mentioned using useEffect so I’ll look into that for now, but if someone could demonstrate with the below or prices additional guidance that would be great!

Original: So I have a piece of state (editableSalesperson) set to an empty object that I want to update with an existing object using setEditableSalesperson and pass into my ModifySalespersons component to edit it, but the update action isn't actually updating the state.

When I run editSalesPerson I see the object getting fed in properly in the console log, but then when it hits setEditableSalesperson(salesperson); and I check the state value in the console log in the next line, it is still empty and hasn't changed.

Here's the code. I tried to strip it down to the relevant info, but if you need more info then I can post it.

import React from 'react';

function Salespersons(props){
  const [editableSalesperson, setEditableSalesperson] = React.useState({})

  function editSalesPerson(salesperson){
    console.log(salesperson);

    setEditableSalesperson(salesperson);
    console.log(editableSalesperson);
  }

  return (
    <>   
      <ModifySalespersons
        isOpen={isOpen}
        setIsOpen={setIsOpen}
        salesperson={editableSalesperson}
        onSubmit={handleSubmit}
        />
       {/* code here */}
      <td className="px-6 py-4 whitespace-no-wrap text-right text-sm leading-5 font-medium">
        <button onClick={ () => editSalesPerson(salesperson) } className="text-indigo-600 hover:text-indigo-900">Edit</button>
      </td>

    </>
  );
}

export default Salespersons;
Paul DeVito
  • 1,542
  • 3
  • 15
  • 38
  • 2
    It doesn't change immediately, it changes on next render. Keep in mind that it's declared with a `const`, so it can't be reassigned in the current scope anyway – CertainPerformance Sep 21 '20 at 15:09
  • 1
    I was typing an answer and someone closed it and I cant post answer. I use useEffect to overcome this. Also the question linked as duplicate does not use hooks so its really not an answer. This question clearly says `hook` Good luck :) – Kal Sep 21 '20 at 15:13
  • Thanks, will look into this. Just posted a clarified question if you’d like to contribute there – Paul DeVito Sep 21 '20 at 15:25
  • 2
    Have you checked this: https://stackoverflow.com/q/54069253/5468463 – Vega Sep 21 '20 at 15:39
  • Like I said in my first comment, useEffect is the answer which I was posting. Vega's comment above links you to the correct answer for your question :) – Kal Sep 21 '20 at 19:44
  • 1
    Yup, @Vega ‘s comment looks to cover it. Sore coats if – Paul DeVito Sep 21 '20 at 19:54

0 Answers0