TypeError: can't access property "map", data.record is undefined

Viewed 255

I am try to add and update the data using reactjs and node js and mysql database. here is my code.

For connection I am created REST API in node js.

connection successfully implemented.

here is my front-end code

for adding data to the database

const App1 = () =>{

const [data,setData] = useState({
    name: '',
    location: '',
    record: [],
    showAlert: false,
    alertMsg: "",
    alertType: "success",
    id:"",
    update: false,
 });

useEffect(()=>{
  fetchData(); 
},[]);

// const [location,setLocation] = useState({location: ''});

const InputEvent = (event) =>{
    const {name, value} = event.target;
    setData((preValue)=>{
        return{
            ...preValue,
            [name]: value,
        };
    });
};

    const addData = () =>{
    var myHeaders = new Headers();
   myHeaders.append("Content-Type","application/json")

   var body = JSON.stringify({name: data.name, location: data.location});

   fetch("http://localhost:8000/api/create",{
       method: "POST",
       headers: myHeaders,
       body: body
   }).then((res)=>res.json())
    .then((result)=>{
        console.log(result);
        
        setData({
            name:"",
            location: "",
            showAlert: true,
            alertMsg: result.res,
            alertType: "success",
            record: result.res,
        });
    });
};

for fetch the all records from database

    const fetchData = () =>{
    var headers = new Headers();
    headers.append("Content-Type","application/json");

    fetch("http://localhost:8000/api/view",{
        method: "GET",
        headers: headers,
}).then((res)=>res.json())
.then((result)=>{
    console.log("result",result);

    setData({
        record: result.res,
    })
}).catch((err)=> console.log("Error",err))};

For edit the data from database in this I am facing the issue to edit the data because when click on edit button data is updated in database but in front-end error is occurred = "can't access property "map", data.record is undefined"

code for edit function

const editTask = (id) =>{
fetch("http://localhost:8000/api/view/"+id,{
    method: "GET",
}).then((res)=>res.json())
.then((result)=>{
    console.log(result);

    setData({
        id: id,
        update: true,
        record: result.res,
        name: result.res[0].name,
        location: result.res[0].location,
    });
}).catch((err)=>console.log("Error",err));};

Now come to update part

here is update function same error is occurred="TypeError: can't access property "map", data.record is undefined

update function as follows

 const updateTask = () =>{
  var myHeaders = new Headers();
  myHeaders.append("Content-Type","application/json");

  var body = JSON.stringify({id: data.id, name: data.name, location: data.location});
  fetch("http://localhost:8000/api/update",{
      method: "PUT",
      headers: myHeaders,
      body: body
  }).then((res)=>res.json())
  .then((result)=>{

    console.log(result);
      setData({
          showAlert: true,
          alertMsg: result.res,
          alertType: "success",
          update: false,
          id: "",
          name: "",
          location: "",
      });
          fetchData();
  }).catch((err)=>console.log("Error",err));};

now come to return part where I write the map method code

data.record.map((record)=>{
                            return(
                                
                                <tr>
                                    <td>{record.id}</td>
                                    <td>{record.name}</td>
                                    <td>{record.location}</td>

                                    <td>
                                       <Button variant="info"onClick{()=>editTask(record.id)}>Edit</Button>
                                    </td>

                                    <td>
                                        <Button variant="danger">Delete</Button>
                                    </td>
                                </tr>
                            );

please help me and thank you

1 Answers

The object you passed to setData after update has no 'record' data. Hence, it becomes undefined.

setData({
  showAlert: true,
  alertMsg: result.res,
  alertType: "success",
  update: false,
  id: "",
  name: "",
  location: "",
});

Assuming your update api returns updated data, you will need to update your 'record' data with the updated data

fetch("http://localhost:8000/api/update", {
  method: "PUT",
  headers: myHeaders,
  body: body
})
.then((res) => res.json())
.then((result) => {
  setData({
    showAlert: true,
    alertMsg: result.res,
    alertType: "success",
    update: false,
    id: "",
    name: "",
    location: "",
    record: data.record.map(item => (item.id === result.id ? result : item)
  });
});
Related