Search code examples
reactjsreact-hooksuse-effect

React Hooks: Referencing data that is stored inside context from inside useEffect()


I have a large JSON blob stored inside my Context that I can then make references to using jsonpath (https://www.npmjs.com/package/jsonpath)

How would I go about being able to access the context from inside useEffect() without having to add my context variable as a dependency (the context is updated at other places in the application)?

export default function JsonRpc({ task, dispatch }) {
  const { data } = useContext(DataContext);
  const [fetchData, setFetchData] = useState(null);

  useEffect(() => {
    task.keys.forEach(key => {
      let val = jp.query(data, key.key)[0];
      jp.value(task.payload, key.result_key, val);
    });
    let newPayload = {
      jsonrpc: "2.0",
      method: "call",
      params: task.payload,
      id: "1"
    };

    const domain = process.env.REACT_APP_WF_SERVER;
    let params = {};
    if (task.method === "GET") {
      params = newPayload;
    }
    const domain_params =
      JSON.parse(localStorage.getItem("domain_params")) || [];
    domain_params.forEach(e => {
      if (e.domain === domain) {
        params[e.param] = e.value;
      }
    });
    setFetchData({ ...task, payload: newPayload, params: params });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [task]);

}

Solution

  • thanks for your reply @Jolly! I found a work around:

    I moved the data lookup to a state initial calculation:

    const [fetchData] = useState(processFetchData(task, data));
    

    then im just making sure i clear the component after the axios call has been made by executing a complete function passed to the component from its parent.

    This works for now, but if you have any other suggestions id love to hear them!