Home > Mobile >  RTK Query response state
RTK Query response state

Time:08-15

I'm trying to convert some Axio code to RTK query and having some trouble. The 'data' response from RTK query doesn't seem to act like useState as I thought.

Original axio code:

const [ importantData, setImportantData ] = useState('');
useEffect(() => {
    async function axiosCallToFetchData() {
        const response = await axiosAPI.post('/endpoint', { payload });
        const { importantData } = await response.data;
        setImportantData(importantData);
    }

    axiosCallToFetchData()
        .then((res) => res)
        .catch((error) => console.log(error));
}, []);

const objectThatNeedsData.data = importantData;

New RTK Query code

const { data, isSuccess } = useGetImportantDataQuery({ payload });
if(isSuccess){
    setImportantData(data.importantData);
}

const objectThatNeedsData.data = importantData;

This however is giving me an infinite render loop. Also if I try to treat the 'data' object as a state object and just throw it into my component as:

const objectThatNeedsData.data = data.importantData;

Then I get an undefined error because it's trying to load the importantData before it's completed. I feel like this should be a simple fix but I'm getting stuck. I've gone through the docs but most examples just use the if statement block to check the status. The API calls are being made atleast with RTK and getting proper responses. Any advice?

CodePudding user response:

Your first problem is that you always call setImportantData during render, without checking if it is necessary - and that will always cause a rerender. If you want to do that you need to check if it is even necessary:

if(isSuccess && importantData != data.importantData){
    setImportantData(data.importantData);
}

But as you noticed, that is actually not necessary - there is hardly ever any need to copy stuff into local state when you already have access to it in your component.

But if accessing data.importantData, you need to check if data is there in the first place - you forgot to check for isSuccess here.

if (isSuccess) {
  objectThatNeedsData.data = data.importantData;
}

All that said, if objectThatNeedsData is not a new local variable that you are declaring during this render, you probably should not just modify that during the render in general.

  • Related