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){
<span class="hljs-keyword">const</span> url = <span class="hljs-string">`<span class="hljs-subst">${CVE_URL}</span>api/cve/<span class="hljs-subst">${cve}</span>`</span>;
<span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-params">dispatch</span> =></span> {
dispatch(getData());
fetch(PROXY + url)
.then(<span class="hljs-function"><span class="hljs-params">blob</span> =></span> blob.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =></span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Request: '</span>, data);
dispatch(getDataSuccess(data))
})
.catch(<span class="hljs-function"><span class="hljs-params">e</span> =></span> {
<span class="hljs-built_in">console</span>.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, ...<span class="hljs-keyword">state</span>}
case FETCH_SUCCESS: return [action.payload, ...<span class="hljs-keyword">state</span>]
case ERROR: return {payload:[], error: true, ...<span class="hljs-keyword">state</span>}
}
return <span class="hljs-keyword">state</span>;
}
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.
#reactjs #redux