0

I'm using a context provider with useReducer in it,


const Project_settings_context = createContext()

...

export const SettingsProvider: FC<TSettingProvider> = ({ children }) => {
    const [loading, setLoading] = useState(true);
    const [settingData, dispatch] = useReducer(reducer, initialState);

    ...

    const value = {
        settingData,
        dispatch,
    };

    return (
        <Settings_context.Provider value={value}>
            {children}
        </Settings_context.Provider>
    );

}

export const useSetting = () => return useContext(Settings_context);

I'm dispatching a data in useEffect return method ( its for the purpose of saving data upon tab switching, and when component unmounts )

useEffect(() => {
    return () => {
        const currentData = getValues();
        dispatch({
            type: settingPage,
            data: currentData[setting],
        });
    };
}, []);

and in a final Tab ( sort of like displaying all ) I'm accessing the data within useEffect

const FinalTab = () => {
    const { settingData } = useSetting()

    useEffect(() => {
        console.log(settingData) 
// !!! this above line returns {} or blank for the last tab I switched ( last dispatch call )
    }, [])

   ...

}

my goal is to send request to server upon displaying the final tab, but its not working as intended, when i reload the page it works fine.

also when i log the data with useEffect with [settingData] as 2nd argument, it shows data the 2nd time it loads but i can't use it & check if all data is present.

is there anyway i can check if the data is finished loading / applying state update ? or any workaround to get instant data ?

codesandbox : https://codesandbox.io/s/usereducer-behaviour-o6ejv

Adharsh M
  • 2,961
  • 3
  • 16
  • 23

1 Answers1

0

Using an empty dependency list mean it will load only once. Adding [settingData] will call useEffect everytime settingData is changed.

const FinalTab = () => {
    const { settingData } = useSetting()

    useEffect(() => {
        console.log(settingData) 
// !!! this above line returns {} or blank for the last tab I switched ( last dispatch call )
    }, [settingData])

   ...

}
Someone Special
  • 12,479
  • 7
  • 45
  • 76
  • that's correct but since I'm planning to add a server request inside that useEffect, I don't want to send the request twice (now the settingData loads twice as i mentioned) . so I am wondering if i can know if dispatch is happening or finished. – Adharsh M Apr 13 '21 at 07:53
  • then use const { loading } = useSettings, and add loading as dependency – Someone Special Apr 13 '21 at 07:54
  • in order to use that, how to know if the state update is happenning / finished ? – Adharsh M Apr 14 '21 at 08:55