Brute
Brute

Reputation: 141

How to get value from an object store in a state in React?

ConsoleI am trying to make a PUT call for which I get the data by id and store it in a state called "getData". I can filter and map over that but I can't seem to extract individual values out of this data, for example, getData.firstName will give me an error stating "getData is not defined". However you can see in the console that this is an array.

I tried filtering the object out of getData(which seems redundant because it has only one object in the array) but filteredObject.firstName throw an error "filterObject is not defined" however you can see in the console that this is an array.

I need to get the key-value pairs individually so that I can compare them in my handleFirstName, handleLastName etc function.

import React, { useState,useEffect, usePrevious} from "react";
import { Link, useParams } from "react-router-dom";
import Axios from "axios";

export default function EditContact(props) {

  const [firstName, setFirstName] = useState();
  const [lastName, setLastName] = useState();
  const [phone, setPhone] = useState();
  const [email, setEmail] = useState();
  const [getData, setGetData] = useState();
  const {id}=useParams()
 
 console.log("ID from Params",id)

 const getDataByID=()=>{
  Axios.get(`http://localhost:5000/get/contacts/${id}`).then((response)=>{
    setGetData(response.data)
    console.log("Get Contact by ID",response.data)
  })
  .catch((error)=>{console.log(error)})
}
useEffect(()=>{
  getDataByID();

},[])

console.log("DataArray",dataArray)
console.log("GetData State",getData)
const filteredObject = getData&&getData.filter((item)=>{return(item.id===id)})  
console.log("Filtered Object",filteredObject)
const handleFirstName = (e) => {
    setFirstName(e.target.value);
  };
  const handleLastName = (e) => {
    setLastName(e.target.value);
  };
  const handlePhone = (e) => {
    setPhone(Number(e.target.value));
  };
  const handleEmail = (e) => {
    setEmail(e.target.value);
  };

  const putData = () => {
    const updateValues = {
      id:id,
      firstName: firstName,
      LastName: lastName,
      phone: phone,
      email: email,
    };
    console.log("UPDATE Values", updateValues);
    Axios.put(`http://localhost:5000/edit/contacts/${id}`, updateValues)
      .then((response) => {
        console.log("Edited Data", response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  // useEffect(()=>{
  //   putData();
  // },[])
  //  value={getData.firstName}
  return (
    <main className="editData">
      {getData&&getData.map((item,idx)=>{
          
            return(
              <div key={idx}>
         
        <form className="editData__form" onSubmit={(e)=>e.preventDefault()}  >

        <input className="editData__formInput" onChange={handleFirstName} defaultValue={item.firstName || {handleFirstName}} />

        <input className="editData__formInput" onChange={handleLastName} defaultValue={item.lastName || {handleLastName}} />

        <input className="editData__formInput" onChange={handlePhone} defaultValue={item.phone || {handlePhone}} />
        
        <input defaultValue="editData__formInput" onChange={handleEmail} defaultValue={item.email || {handleEmail}} />
       
      </form>
      <Link to='/contacts'>Back To Contacts</Link>
      </div>
      )
      })
    }
     <button onClick={putData}>PUT DATA</button>
     {usePrevious}
        <button onClick={getDataByID}>Get DATA</button>
    </main>
  );
}

Upvotes: 0

Views: 832

Answers (1)

Huan
Huan

Reputation: 48

According to the console, your data seems to be of Array type. Therefore, you must access your desired data item first before accessing a specific data property.

E.g. getData[0].firstName

Your "not defined" error probably comes from the first render.

Remember useEffect runs after every render.
And your console.log is written directly in the rendering logic, which makes they to be called in every render.
So this means your console.log are called before the first calling time of useEffect.

Have a look at the value of your state if useEffect hasn't been called yet. getData have its initial value of undefined. Accessing a property of an undefined value will issue an error.

A solution for this is specifying an initial value of your getData state, which should be [].

Upvotes: 1

Related Questions