Search code examples
reactjsjsonrtk-query

RTK Query SyntaxError JSON.parse: unexpected non-whitespace character after JSON data


I'm working on a React component that has to make a series of RTK Query calls, one of which is to get the ID of a related document for another query to use as its arg. Where I'm stuck is I'm getting the error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 3 of the JSON data". Below is the returned log from the query which shows the exact data I'm trying to get as the returned data. I'm at a total loss since I've no idea what the particular offending character is. Postman returns the same string (without the quote marks) without any trailing characters.

status:"rejected"
endpointName:"getCurrentPlan"
requestId:"GTR3VTWcO7pIyc2UBWGVs"
originalArgs:"6205a8313fe12d6b4ec354c4"
startedTimeStamp:1661294881186
status:"PARSING_ERROR"
originalStatus:200
data:"62c9d3f6053cf23ca515fad1"
error:"SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 3 of the JSON data"

The query call itself is very simple:

getCurrentPlan: builder.query({
            query: clientId => `/clientapi/clients/${clientId}/plan`,

        })

and the backend works fine. And nothing special with the call in the component:

const {data: planId, isSuccess: planSuccess} = useGetCurrentPlanQuery(clientId)

So I just don't know where to start trying to resolve this. Any direction would be greatly appreciated.

Slight Update In response to the comment by @user4980215, here is the backend method. The stored value for the client model's currentPlan field is just a string, so in the case of my test call, 62c9d3f6053cf23ca515fad1. This matches what RTK Query is showing as the data in the response, which again is what leads to my confusion for the invalid JSON error.

exports.getCurrentPlan = async (req, res) => {
    try {
        const { id } = req.params;
        const client = await Client.findById(id);
        const plan = client.currentPlan;
        res.send(plan);
    } catch {
        res.status(404)
        res.send({ error: "Current Plan not found"})
    }
}

Solution

  • Based on the conversation above and this answer.

    Parsing a Response:

    By default, fetchBaseQuery assumes that every Response you get will be parsed as json. In the event that you don't want that to happen, you can specify an alternative response handler like text

    So the working solution would be:

    getCurrentPlan: builder.query({
      query: (clientId) => `/clientapi/clients/${clientId}/plan`,
      responseHandler: "text",
    });