I am trying to figure out a way of using a piece of data returned from RTK query in a slice as default state.
Let's say I have this data returned from an API call and I use RTK query to get the data.
const data = {
name: "Test Employee",
options: {..},
badges: {..}
age: 26,
id:1,
isEmployee: options && badges
}
NOTE: isEmployee is either true or false based on the options and badges property which is part of the returned data from the API
I am able to use this data in the component by doing this:
const Employee = () => {
const {data} = useGetEmployee(null)
return <div>{data.name}</div>
}
Now, I have a component where I need to do some conditional rendering based on isEmployee
flag by calling the toggleEmployee
action which basically toggles the isEmployee
flag.
So I create a slice like this:
const initialState = {
isEmployee: ??? // how to set the default state here as it depends on options and badges properties returned from the RTK query
};
export const employeeSlice = createSlice({
name: "employeeSlice",
initialState,
reducers: {
toggleEmployee: (state, action) => {
state.isEmployee = action.payload;
},
},
});
I am new RTK query and trying to figure out what's the best/recommended way to achieve this. Any help is appreciated, thanks!
The correct approach would be to use the same useGetEmployeeQuery(null)
hook. Since that is your source of truth, there is no need to keep double state.
Assuming you are using the useQuery hook to reach the isEmployee data in every other place (the useQuery hook initiates a request and subscribes to the state).
The data is cached by default so long as there are mounted "subscribers" to the query. Then it will refetch every 5 minutes, but caching can be configured for every endpoint.
The way I would do this is by creating a custom hook for getting the value of isEmployee
const useIsEmployee = () => {
const {data} = useGetEmployee(null);
return data.isEmployee();
}
Then you use this hook in every other component that depends on isEmployee
, and since there is already state for the argument null
the data will already be in cached for the endpoint.
https://redux-toolkit.js.org/rtk-query/api/created-api/hooks#usequery read the description part here, that will help you understand the concepts of rtk-query better. There is also useQueryResults
, but I default to useQuery
since that will fetch the data if it's not already there.
Hope this helps