Search code examples
reactjsreduxreact-reduxredux-thunk

Why is Thunk-Redux turning an object into a string?


I've come across a strange issue with thunk-redux. I am writing a React-Redux app that calls a public API, and displays the data in a table. However, when I incorporated thunk middleware to handle the asynchronous API calls, my data is being stringified after the action is dispatched to the reducer.

index.js (action creator)

export const FETCHING_DATA = 'FETCHING_DATA';
export const FETCH_SUCCESS = 'FETCH_SUCCESS';
export const ERROR = 'ERROR';

export const getData = () => {
    return {
        type : FETCHING_DATA
    }
}

export const getDataSuccess = (data) => {
    return {
        type : FETCH_SUCCESS,
        payload: data
    }
}

export const getDataFailure = () => {
    return {
        type : ERROR
    }
}

export function searchCVE(cve){
    
    const url = `${CVE_URL}api/cve/${cve}`;
    return dispatch => {
        dispatch(getData());

        fetch(PROXY + url)
        .then(blob => blob.json())
        .then(data => {
            console.log('Request: ', data);
            dispatch(getDataSuccess(data))
        })
        .catch(e => {
            console.log(e);
            dispatch(getDataFailure(e.message))
        });

    }
}

data_reducer.js (reducer)

import {FETCHING_DATA ,FETCH_SUCCESS, ERROR } from '../actions/index.js';

const initialState = {
    payload:[],
    fetching: false,
    error: false
}
export default function(state=initialState, action){
    console.log('Got CVE: ', action);

    switch (action.type){
        case FETCHING_DATA: return {payload:[], fetching: true, ...state}
        case FETCH_SUCCESS: return [action.payload, ...state]
        case ERROR: return {payload:[], error: true, ...state}
             
    }
    return state;

}

As you can see in the index.js action creator, console.log('Request: ', data); displays the JSON object I want. However, when I {console.log('TEST: ' + this.props.cve)} in my table component, the console shows:

TEST: [object Object]

At no point in my app am I "stringifying" my data - why/where could thunk-redux be turning my data into a string? I thank the community for any insight it can provide.


Solution

  • At no point in my app am I "stringifying" my data - why/where could thunk-redux be turning my data into a string?

    redux-thunk couldn't do that under no circumstances. It's deadly simple; all it's doing is processing function action in a different way.

    The problem is that the object is being stringified by you, + addition operator coerces an object to a string:

    {console.log('TEST: ' + this.props.cve)}
    

    In case an object is expected to be displayed in the console, it should be:

    {console.log('TEST: ', this.props.cve)}
    

    Or it can be displayed in DOM:

    <pre>{JSON.stringify(this.props.cve, null, 2)}</pre>