Home > OS >  Response gets lost after being sent from server
Response gets lost after being sent from server

Time:02-04

I am using react for frontend and Express from server. Also i am using redux-toolkit for state management.

My react application has a component which on render dispatches a reducer using useEffect. This reducer makes a request to my server to get required data.

When i am making this request from postman i am getting 200 OK as status and i receive required json data as response.

When i am making the same request from my react app, my request is correctly sent to the server and when i console log the generated response in my Express server the response console logs correctly. But when i see my react dev tools it shows that my request is rejected and i see no response in dev tools. When i console log the received response i get undefined as output.

Below i my component which dispatches a reducer on render:

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { getIssuedBooks } from '../../features/user/userSlice'
import BooksUser from './BooksUser';

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';

const UserIssuedBooks = () => {
  const { userIssued, isLoading } = useSelector((state) => state.user)
  const dispatch = useDispatch()
  useEffect(() => {
    const promise = dispatch(getIssuedBooks())
    return promise.abort()            // this is to prevent any memory leaks
  }, []);

  return (
      <Box>
        {userIssued.length === 0 ? <Typography sx={{ textAlign: 'center' }}>You have Not Issued any Books</Typography> : userIssued.map((book, index) =>
        <BooksUser book={book} key={index} />
      )}
      </Box>
  )
}

export default UserIssuedBooks

Below is my piece of my Slice.js builder which handles the request stages:

.addCase(getIssuedBooks.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getIssuedBooks.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.userIssued = action.payload;
        console.log(action.payload)
      })
      .addCase(getIssuedBooks.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
        console.log(action.payload)       // logs undefined
      })

In my network tab one request gets 200 OK preflight and 2 other requests getting cancelled.Refer this. This is my react dev tools screenshot. This is my postman screenshot

I tried finding the root cause for this error and rectify it but i am unable to do so.

CodePudding user response:

I believe we should put a function instance in the return of useEffect, not call the function immediately.

So instead of this:

return promise.abort()

Try to use this instead:

return () => promise.abort()
  • Related