Reputation: 7460
I have a problem with redux-thunk, it just doesn't pass the dispatch to my action creator. I'm logging it but it is still undefined:
Here is my action creator:
import * as types from './actionTypes'
import Service from '../service'
export const fetchFromApi = payload => {
return { type: types.FETCH_FROM_API_TEST, payload }
}
export const fetchApiTestAction = () => dispatch => {
return Service.GetUsers().then( _data => {
dispatch(fetchFromApi( _data.data )) // you can even distructure taht like fetchFromApi(({ data }))
}).catch ( err => {
// error catching here
// you can even call an failure action here...
// but sorry about it , i have no time for that , im sorry :(
throw (err)
})
}
Here is my Service.js class
// Basic fetch
async basicFetch(url, options, headers = this.authernticateHeader) {
let fetchOptions = {}
if(options.headers) {
fetchOptions = {
mode: 'cors',
cache: 'default',
...options
}
} else {
fetchOptions = {
mode: 'cors',
cache: 'default',
...options,
headers
}
}
// log before sending the request...
// console.log(url, fetchOptions, fetchOptions.headers.get('Content-Type') )
try {
const response = await fetch(
`${this.serverAddress}${url}`,
{ ...fetchOptions }
)
if(!response.ok) {
throw {
message: response.statusText,
api: `${options.method} ${this.serverAddress}`
}
}
const responseJson = await response.json()
console.log('----------------------------')
console.log(responseJson)
console.log('----------------------------')
return responseJson
} catch(err) {
throw { ...err }
}
}
GetUsers = () => {
return this.basicFetch(this.urls.GET_USERS, {
method: 'GET'
})
}
Here is my routes.js file
import { fetchApiTestAction } from './actions/fetchApiTestAction'
const routes = [
{
path: '/',
exact: true,
component: Home,
fetchInitialData: fetchApiTestAction()
},
{
path: '/about',
component: About
},
{
path: '/contact',
component: Contact
},
]
And here is my server.js file
app.get('/*', (req, res, next) => {
const activeRoute = routes.find( route => matchPath(req.url, route) ) || {}
const _promise = activeRoute.fetchInitialData
? activeRoute.fetchInitialData()
: Promise.resolve()
_promise.then( () => {
const store = configureStore()
const markup = renderToString(
<StaticRouter location={req.url} context={{}}>
<Provider store={store}>
<App />
</Provider>
</StaticRouter>
)
const initialBrowserTabText = 'hi there from home page...'
const initialState = store.getState() || {}
const _template = template( initialBrowserTabText, initialState, markup )
res.send(_template)
}).catch(err => {
console.log(err)
})
})
I haven't faced this kind of problem so far. When I console.log(dispatch)
inside of my action creator (before return
part) it is undefined. I should say that here is what my terminal shows to me:
Server is listening on port 8000...
----------------------------
{ page: 1,
per_page: 3,
total: 12,
total_pages: 4,
data:
[ { id: 1,
first_name: 'George',
last_name: 'Bluth',
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg' },
{ id: 2,
first_name: 'Janet',
last_name: 'Weaver',
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg' },
{ id: 3,
first_name: 'Emma',
last_name: 'Wong',
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg' } ] }
----------------------------
TypeError: dispatch is not a function
at eval (webpack-internal:///./src/js/actions/fetchApiTestAction.js:17:7)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
This means that I'm getting the data from api, but why dispatch is not a function?
Upvotes: 1
Views: 501
Reputation: 13071
That won't work unless you pass the redux-store dispatch
property when you invoke fetchInitialData
... Something like this:
const _promise = activeRoute.fetchInitialData
? activeRoute.fetchInitialData(store.dispatch)
: Promise.resolve()
The real problem is that your redux-store doesn't even exist at that point, because you are configuring it after that promise has finished... So that's something else that you will have to address.
Upvotes: 2