reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.65k stars 1.16k forks source link

Get an error "jwt malformed" within some services, but is working elsewhere. #3093

Closed Kse-Nia closed 1 year ago

Kse-Nia commented 1 year ago

Hi, I'm creating a CRUD project (with auth) using react and redux toolkit. I have a header with token to give authorization. What I can't understand is that header "config" with token is working without issues inside some services, but not in others. For example, my postService to update a post is :

const updatePost = async (postData, PostId, token) => {
  try {
    const config = {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    };
    const response = await axios.put(
       "http://localhost:8080/api/${postData?.PostId}",
      postData,
      config
    );
    const updateAlert = toast.success("Post updated");
    return [response.data, updateAlert, postData?.PostId];
  } catch (error) {
    console.log("error", error);
  }
};

The postSlice:

const initialState = {
  posts: [],
  isError: false,
  isSuccess: false,
  message: "",
};

export const updatePost = createAsyncThunk(
  "api/update/:id",
  async (postData, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await postsService.updatePost(postData, token);
    } catch (error) {
      console.log(error);
    }
  }
);

export const postsSlice = createSlice({
  name: "post",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(updatePost.success, (state, action) => {
        const { PostId, postData } = action.payload;
        state.post[PostId] = postData;
        state.isLoading = false;
      })
      .addCase(updatePost.rejected, (state, action) => {
        state.isError = true;
        state.message = action.payload;
        state.posts = action.payload;
      });
  },
});

And the Component "updatePost":

const UpdateCardPost = ({ post }) => {
  const dispatch = useDispatch();

  const [content, setContent] = useState("");
  const [imageUrl, setImageUrl] = useState(null);
  const [error, setError] = useState(null);

  const PostId = useParams().id;
  console.log(PostId);

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const postData = { content, imageUrl };
      dispatch(updatePost({ ...postData, PostId }));
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Box>
      <Typography variant="h4">Update Post</Typography>
      <Box component="form" noValidate onSubmit={handleSubmit}>
        <div>
          <Textarea
            name="content"
            value={content}
            onChange={(e) => setContent(e.target.value)}
          />
        </div>
        <div>
          <label htmlFor="fileUpload">Add picture</label>
          <Input
            type="file"
            label="Change picture"
            accept=".jpg, .jpeg, .png, .gif"
            onChange={(e) => setImageUrl(e.target.files[0])}
          />
        </div>
        <Button type="submit">Update</Button>
      </Box>
    </Box>
  );
};

I get an error inside postService " "{\"error\":{\"name\":\"JsonWebTokenError\",\"message\":\"jwt malformed\"}}" . However, I use the same header config everywhere else (create or delete post, likes, comments). Backend is working without problem. Token is stored in LS, so it's just a problem with my service (or .addCase inside slice). I can't comprehend why in some services it works with http://localhost:8080/api/comments/${PostId} and others http://localhost:8080/api/${postData?.PostId}. I make it works in different services by tweaking, but can't understant why it's not working in the same way everywhere.

phryneas commented 1 year ago

I'm not sure what this has to do with Redux Toolkit. You are making those requests with your own code.