Home > other >  Value of props is undefined when accessed inside a function
Value of props is undefined when accessed inside a function

Time:05-30

I have a function which update and add new record to my database. I have passed props called matterId from parent to child component but if I do console log inside the functions, it shows undefined instead.

import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form } from 'react-bootstrap';
 
export default function TimeEntry(props){

    const { matterId, timeEntriesData } = props;
    console.log(`matterId: ${matterId}`)
   
    const [timeEntries, setTimeEntries] = useState([]);


    const addTimeEntry = (e, matterId) => {
        console.log(`matterId: ${matterId}`)
 
        e.preventDefault();
  
        fetch(`http://localhost:4000/matters/628607f1c8a4009f2fd4801e/timeEntry`, {
            method: 'PUT',
            headers: {
                Authorization: `Bearer ${ localStorage.getItem('token') }`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                description: entryDescription
            })
  
        })
        .then(res => res.json())
        .then(data => {
  
            if (data === true) {
  
                // fetchData();
                alert("New time entry successfully aded.");
                closeEdit();
  
            } else {
  
                alert("Something went wrong.");
                closeEdit();
  
            }
  
        });
  
    };
};

console.log shows this: matterId: undefined

CodePudding user response:

You are declaring the variable again in the function signature.

Change it something like this

const addTimeEntry = (e) => {
    console.log(`matterId: ${matterId}`)
    ....

}

CodePudding user response:

const { matterId, timeEntriesData } = props;
// This matterId is from props.
console.log(`matterId: ${matterId}`);

const [timeEntries, setTimeEntries] = useState([]);

const addTimeEntry = (e, matterId) => {
  // This matterId is from function addTimeEntry
  console.log(`functionMatterId: ${matterId}`);
};

// Call function like this
addTimeEntry(e, "id"); // expected console >> functionMatterId: id
  • Related