0

Hello StackOverflow Community

I am trying to update the state of a json object using setState in a child component but its not working. The data attribute is empty. What am I doing wrong?

App.JS

const [userData, setUserData] = useState({
    firstName: "",
    lastName:"",
    email: "",
    code:"",
  })

return (
<div>
<Child parentInfo = {{userData, setUserData}} />
</div>
)

Child.js

function Child({parentInfo}) {
  const client = axios.create({
     baseURL: "http://localhost:7171/api/"
  });

  const handleSubmit = e => {
      e.preventDefault();
      
      client.post('public/someAPI',someData).then((response) => {
        if(response.status === 200){


          parentInfo.setUserData(prevData => ({...prevData,
                code: response.data.code
          })) 
          console.log(parentInfo) //NOT updated
          //Store this data in localstorage but its not updatd??
          //localstorage.setItem('key', parentInfo.userData);

          
      });
  }

  return(
    <header className="form-header">
       <h2>{parentInfo.userData}</h2>
     </header>
     <form className="form flex-col" onSubmit={handleSubmit}>
       
                  <button type="submit" >Submit</button>
     </form>
)
export default Child;

Where response is the same json but filled with some more data. But Code attribute is empty even after doing a setState though reponse.data contains a value for code. eg

response.data = {firstName: "test",
    lastName:"test",
    email: "test",
    code:"123",
}
ksernow
  • 662
  • 3
  • 14
  • 33
  • could you share the code where you defined that `Child` function component? – Amrovic Mar 14 '23 at 01:53
  • its on the app.js – ksernow Mar 14 '23 at 01:54
  • Sorry for the stupid question, I started learning React literally today, but why is your function named `Join`? Isn't the component named ``? –  Mar 14 '23 at 02:03
  • @Megapteranovaeangliae That's what got me confused. Could you share the code in `Child.js`, @ksernow? – Amrovic Mar 14 '23 at 02:04
  • I find this question hard to read. You have code missing from the code you posted. Parts of child.js when you should show the whole component. How can we debug a small section? What if the problem is in the part you did not show us. – Bender Mar 14 '23 at 02:10
  • sorry, updated. – ksernow Mar 14 '23 at 02:11
  • 1
    Logging the current state will not show you the value it will become on the next render. See the duplicate for details and stop using `console.log()` to debug state – Phil Mar 14 '23 at 02:47
  • _`if(response.status === 200)`_... what else would it be? Why bother with this check? – Phil Mar 14 '23 at 02:48
  • How do I debug the state then? Thanks – ksernow Mar 14 '23 at 03:06
  • Just use it in your components. If you get unexpected results in your rendered output, that's when you start debugging. Use the React Dev Tools browser extension – Phil Mar 14 '23 at 06:24

1 Answers1

0

Are you not spreading the old ...prevData? If you don't want to spread it you can just replace it like I put in the code block below

Hey what's up with this line <Child parentInfo = {{userData, setUserData}} /> why isn't it <Child parentInfo={{userData, setUserData}} />?

import axios from 'axios';

function Child({parentInfo}) {
  const client = axios.create({
    baseURL: "http://localhost:7171/api/"
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    const someData = {}; // Add your data here
      
    client.post('public/someAPI', someData)
      .then((response) => {
        if (response.status === 200) {
          parentInfo.setUserData(response.data);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <div>
      <header className="form-header">
        <h2>{parentInfo.userData}</h2>
      </header>
      <form className="form flex-col" onSubmit={handleSubmit}>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default Child;
Bender
  • 103
  • 8
  • I did. I tried doing what you have here but still does not update the state. (Also why do I need to spread the old data when I can replace with new data given the data attributes are same?) – ksernow Mar 14 '23 at 02:23
  • I added some comments in the child.js component. I am trying to person a action after settting state but cannot since setstate is not updated – ksernow Mar 14 '23 at 02:40
  • 1
    @ksernow if you just wanted to replace it with new data. Then just replace it, don't put a function inside. setUserData(response.data);. When you do the function you tend to want the old value as well. – Bender Mar 14 '23 at 06:20