0

What is the best way to find a value in the api request and make it available in the entire application? I need to get the total of unread messages and show it to the user in the application header. Every time you change pages, a new request is made to update the total of unread messages. I'm using a context like this:

/** @format */

import React, { createContext, useContext, useState, useEffect, useRef } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import api from "../services/api";

const BadgeContext = createContext();

export default function BadgeProvider({ children }) {
  const [messageCount, setMessageCount] = useState(0);
  const [userLogged, setUserLogged] = useState("");

  async function getAuthUserFromStorage() {
    try {
      const dataFromStorage = await AsyncStorage.getItem("@ellot:authUserLogged");
      const authUserLogged = JSON.parse(dataFromStorage);
      setUserLogged(authUserLogged.user);
    } catch (e) {
      console.log("ERROR: ", e);
    }
  }

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

  useEffect(() => {
    const getTotalMessageNotRead = async () => {
      try {
        const response = await api.get(`/messages/total-not-read/${userLogged.id}`);
        setMessageCount(response.data.data);
        console.log("messageCount context ", messageCount);
      } catch (error) {
        console.log("Message Not Read Error: ", error);
      } finally {
        console.log("finally message not reader context", messageCount);
      }
    };
    getTotalMessageNotRead();
  }, []);

  async function resetCountMessage() {
    setMessageCount(0);
  }

  const store = {
    messageCount,
    resetCountMessage,
  };

  return <BadgeContext.Provider value={store}>{children}</BadgeContext.Provider>;
}
export function useBadge() {
  const context = useContext(BadgeContext);
  const { messageCount, resetCountMessage } = context;
  return { messageCount, resetCountMessage };
}
Edinho Rodrigues
  • 354
  • 4
  • 24
  • 1
    You can use a state management library like redux or mobx. If you don't / won't have too much global state in your app, you can also use the built-in React [Context Api](https://reactjs.org/docs/context.html) – Ugur Eren Nov 11 '21 at 17:23
  • I'm using context api and the value is available to my entire application. The problem is that I want the context to update the information coming from the api every time the user changes the page. See the code tha I edited. – Edinho Rodrigues Nov 11 '21 at 17:41
  • Solution is to write a function in the root of your project directory, say in App.js and then pass this function as a callback to the navigation such that it can be accessed by every class/screen in your project. Then call this function in componentDidMount in each class. If you want the function to run every time a newly or already loaded screen is opened, you might wanna call the callback from shouldComponentUpdate() and add a case on isFocussed listener using withNavigationFocus in-built function. Refer to this link: https://reactnavigation.org/docs/4.x/function-after-focusing-screen/ – Gavin D'mello Nov 11 '21 at 20:28
  • I tried doing this with hooks and @react-navigation/native but it didn't work. – Edinho Rodrigues Nov 11 '21 at 23:24

0 Answers0