Home > Software engineering >  React Parent Function Called from Child Component does not Update State?
React Parent Function Called from Child Component does not Update State?

Time:06-12

I'm stuck on having my child component: ChildButton call its parent component: ParentTable's function that contains a "setState", to then refresh or update the table itself (in the parent).

I am passing a getData function from the parent to the child through props. On button click in the child - call a function to; close a dialog, do a PUT on a mock api datastore, then call the getData function. The getData function does a GET from the api and does a setState on "apiData". Problem is the data is not updating in the parent table even though the getData function is being called.. Don't state changes cause a reload? Code below:

ParentTable.jsx

export default function ParentTable() {
    **const [apiData, setAPIData] = useState([]);**

    const getData = () => {
        axios.get(`https://blah.mockapi.io/fakeData`)
            .then((getData) => {
                **setAPIData**(getData.data);
            })
        console.log('getData'); // fires on child button click
        }

    return (
        <Table..
            <Table.Body>
                {**apiData**.map((obj) => {
                    <Table.Cell>bunch of data from the obj..
                    <Table.Cell><ChildButton **getData={getData}**</Table.Cell>
                    
        ... />../>../>
    )
}

export default ParentTable;

ChildButton.jsx

const ChildButton = ({getData, ...}) => {
    function handleClose() {
        setOpen(false)
        axios.put(`https://blah.mockapi.io/fakeData/${id}`, {
            ...
        })
        **getData()**

    }

    return (
        <Button onClick={handleClose} ...>
            Update
        </Button>
    )
}

export default ChildButton;

Long story short - why is my change of state in the Parent Component not updating it's table data?

CodePudding user response:

Axios.put returns a promise and you are not waiting for the response. Invoke the getData function inside the .then function or use async await:

 axios.put(`https://blah.mockapi.io/fakeData/${id}`, {
            ...
        }).then(() => **getData()**)
        
  • Related