Skip to content
Advertisement

How to update my useEffect hook when State change happen in a different .js file’s component in ReactJS?

I am trying to make an API call in useEffect() and want useEffect() to be called everytime a new data is added in the backend. I made a custom Button(AddUserButton.js) which adds a new user in backend. I am importing this button in the file (ManageUsers.js) where I am trying to display all the users. I just wanted to make an useState to keep track everytime an add button is clicked and make useEffect refresh according to it. For Example:

const [counter, setCounter] = useState(0);
...
const handleAdd = () => {
  setCounter(state => (state+1));
};
...
useEffect(() => {
 // fetch data here
 ...
}, [counter]);
...
return(
 <Button onClick = {handleAdd}> Add User </Button>

);

But currently because I have two .js files, I am not sure how to make my logic stated above work in this case

ManageUsers.js

import AddUserButton from "./AddUserButton";
...
export default function ManageShades() {
...
useEffect(() => {
  axios
  .get("/api/v1/users")
  .then(function (response) {
    // After a successful add, store the returned devices
    setUsers(response.data);
    setGetUserFailed(false);
  })
  .catch(function (error) {
    // After a failed add
    console.log(error);
    setGetUserFailed(true);
  });
console.log("Load User useeffect call")

 },[]);
 return (
<div>
  ...
    <Grid item xs={1}>
      
      <AddUserButton title = "Add User" />
      
    </Grid>
  ...
</div>
);
}

AddUserButton.js

export default function AddDeviceButton() {
...

return (
 <div>
  <Button variant="contained" onClick={handleClickOpen}>
    Add a device
  </Button>
 ...
 </div>
 );
} 

Advertisement

Answer

A common approach is to pass a callback function to your button component that updates the state of the parent component.

import { useState, useEffect } from "react";

const AddUserButton = ({ onClick }) => {
  return <button onClick={onClick} />;
};

export default function Test() {
  const [updateCount, setUpdateCount] = useState(false);
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count++);
  }, [updateCount]);

  return (
    <div>
      <AddUserButton
        onClick={() => {
          // do something, e.g. send data to your API
          // finally, trigger update
          setUpdateCount(!updateCount);
        }}
      />
    </div>
  );
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement