react redux and thunks / axios / is not a function - reactjs

Hello I have the following error when trying to consume my api
TypeError: api.get is not a function
api.js
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8000', });
export default api;
action fetch:
const api = require('../../services/api');
export function productsError(bool) {
return {
type: 'PRODUCTS_HAS_ERRORED',
hasErrored: bool
};
}
export function productsIsLoading(bool) {
return {
type: 'PRODUCTS_IS_LOADING',
isLoading: bool
};
}
export function productsFetchSuccess(products) {
return {
type: 'PRODUCTS_SUCCESS',
products
};
}
export function errorAfterFiveSeconds() {
// We return a function instead of an action object
return (dispatch) => {
setTimeout(() => {
// This function is able to dispatch other action creators
dispatch(productsError(true));
}, 5000);
};
}
export function ProductsFetchData() {
return (dispatch) => {
dispatch(productsIsLoading(true));
api.get('/products')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(productsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((products) => dispatch(productsFetchSuccess(products)))
.catch(() => dispatch(productsError(true)));
};
}
reducer fetch
export function ProductsHasErrored(state = false, action) {
switch (action.type) {
case 'PRODUCTS_HAS_ERRORED':
return action.hasErrored;
default:
return state;
}
}
export function ProductsIsLoading(state = false, action) {
switch (action.type) {
case 'PRODUCTS_IS_LOADING':
return action.isLoading;
default:
return state;
}
}
return action.products;
default:
return state;
}
} return action.products;
default:
return state;
}
}export function Products(state = [], action) {
return action.products;
default:
return state;
}
} return action.products;
default:
return state;
}
}
my store :
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
}
in my app:
import React, { Component } from 'react'
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux';
import { ProductsFetchData } from '../../store/actions/productsFetch';
class index extends Component {
componentDidMount() {
this.props.fetchData('/products');
}
render() {
if (this.props.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <p>Loading…</p>;
}
return (
<div>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
products: state.products,
hasErrored: state.itemsHasErrored,
isLoading: state.itemsIsLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: () => dispatch(ProductsFetchData())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(index);
basically I have error in this function:
export function ProductsFetchData() {
return (dispatch) => {
dispatch(productsIsLoading(true));
api.get('/products')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(productsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((products) => dispatch(productsFetchSuccess(products)))
.catch(() => dispatch(productsError(true)));
};
}
I don't know why or where I went wrong to get this error

in action fetch, you should be change:
const api = require('../../services/api');
to:
const api = require('../../services/api').default;
or
import api from '../../services/api')

You should just export the baseURL as as const, then in your actions:
import axios from 'axios'
//othercode here
export function ProductsFetchData() {
return (dispatch) => {
dispatch(productsIsLoading(true));
api.get(`${}/products`)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(productsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((products) => dispatch(productsFetchSuccess(products)))
.catch(() => dispatch(productsError(true)));
};
}

When you use export default, This file will create an object with key is default and export them.
const a = 2;
export default a;
import with require:
const a = require(...)
console.log(a)
// a here will be an object
>> Object {default: 2}
So when you want to use require from export default, you have to access to .default: console.log(a.default).
Or you can use import in ES6 like this:
import a from '...';
// console.log(a)
>> 2

Related

Nextjs - await store.dispatch Cannot read property 'dispatch' of undefined

I'm new to React, Redux and have been following tutorials on the topic. I'm come across a lot of issues that I've been able to resolve but I've come across an issue I can't resolve. I set up store, and can even view it through Chrome's Redux Tools and it show correctly, however when I try and dispatch to the Store, I always get a Cannot read property 'dispatch' of undefined error. I have followed numerous tutorials letter for letter, and am still stuck with the same error message.
Index.Js
import Layout from '../components/layout/Layout';
import Home from '../components/Home';
import { getRooms } from '../redux/actions/roomActions';
import { wrapper } from '../redux/store';
export default function Index() {
return (
<Layout>
<Home />
</Layout>
);
}
export const getServerSideProps = wrapper.getServerSideProps(
async ({ req, store }) => {
await store.dispatch(getRooms(req));
}
);
roomConstants.js
export const ALL_ROOMS_SUCCESS = 'ALL_ROOMS_SUCCESS';
export const ALL_ROOMS_FAIL = 'ALL_ROOMS_FAIL';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
reducer.js
import { combineReducers } from 'redux';
import { allRoomsReducer } from './roomReducers';
const reducer = combineReducers({
allRooms: allRoomsReducer,
});
export default reducer;
Store.js
import { createStore, applyMiddleware } from 'redux';
import { HYDRATE, createWrapper } from 'next-redux-wrapper';
import thunkMiddleware from 'redux-thunk';
import reducers from './reducers/reducers';
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
const reducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
return reducers(state, action);
}
};
const initStore = () => {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
};
export const wrapper = createWrapper(initStore);
roomReducer.js
import {
ALL_ROOMS_SUCCESS,
ALL_ROOMS_FAIL,
CLEAR_ERRORS,
} from '../constants/roomConstants';
// All rooms reducer
export const allRoomsReducer = (state = { rooms: [] }, action) => {
switch (action.type) {
case ALL_ROOMS_SUCCESS:
return {
roomsCount: action.payload.roomsCount,
resPerPage: action.payload.resPerPage,
filteredRoomsCount: action.payload.filteredRoomsCount,
rooms: action.payload.rooms,
};
case ALL_ROOMS_FAIL:
return {
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
roomAcion.js
import axios from 'axios';
import absoluteUrl from 'next-absolute-url';
import {
ALL_ROOMS_SUCCESS,
ALL_ROOMS_FAIL,
CLEAR_ERRORS,
} from '../constants/roomConstants';
//Clear errors
export const clearErrors = () => async (dispatch) => {
return dispatch({
type: CLEAR_ERRORS,
});
};
// Get all rooms
export const getRooms = (req) => async (dispatch) => {
try {
const { origin } = absoluteUrl(req);
const { data } = await axios.get(`${origin}/api/rooms`);
dispatch({
type: ALL_ROOMS_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: ALL_ROOMS_FAIL,
payload: error.response.data.message,
});
}
};
in index.js, your getServerSideProps function should read this;
export const getServerSideProps = wrapper.getServerSideProps((store) => async ({ req }) => {
await store.dispatch(getRooms(req));})
Use the old version of next-redux-wrapper like 6.0.2

action payload is not dispatched to reducer

Using react-redux to get items from my database. My reducer is receiving action.type but not action.payload from action. As shown in the redux developer tool here: The response from my database api is working and I have already applied my redux-thunk into my store using applyMiddleware.
Home.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getAvailableItems } from '../Redux/Actions/ItemAction'
componentDidMount() {
this.props.getAvailableItems()
this.props.fetchPosts()
}
render() {
console.log(this.props)
return (<div></div>)
}
const mapStateToProps = state => {
return {
item : state.item.items
}
}
const mapActionsToProps = {
getAvailableItems,
fetchPosts
}
export default connect(mapStateToProps, mapActionsToProps)(Home)
ItemAction.js
export const getAvailableItems = () => dispatch => {
console.log("running itemAction")
fetch('https://us-central1-firebaselink.cloudfunctions.net/api/items')
.then(
(res) => {
//console.log(res.json())
res.json()
})
.then(data => dispatch(
{
type : 'GET_ALL_AVAILABLE_ITEMS',
payload : data
//console.log(data)
}
))
.catch((err) => console.log(err));
}
itemReducer.jsx
const initState = {
items : []
}
const itemReducers = (state = initState, action) => {
//return state;
console.log(action.type)
switch(action.type){
case 'GET_ALL_AVAILABLE_ITEMS':
console.log("this is the payload : "+action.payload)
return{
...state,
items: action.payload
}
default:
return state;
}
}
export default itemReducers;

Infinite loop when fetch data in middleware

I try to fetch data and display it into a react component, but i have an infinite loop on the fetch call in my middleware and action seems not dispatched. i Receive no result in my post component.
Action.js :
import { DATA_LOADED } from './../constants/action-types';
export function getData() {
return {type: DATA_LOADED}
}
Middleware :
export function asyncMiddleWare({dispatch}) {
return function(next) {
return function (action) {
if (action.type === DATA_LOADED) {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => {
console.log('---');
console.log('infinite calls');
console.log('---');
dispatch({type:DATA_LOADED, payload: json});
})
}
return next(action);
}
}
}
Reducer :
if (action.type === DATA_LOADED) {
return Object.assign({}, state, {
articles: state.remoteArticles.concat(action.payload)
})
}
and the store
import {createStore, applyMiddleware, compose} from 'redux';
import rootReducer from '../reducers/index';
import {asyncMiddleWare } from "../middleware";
import thunk from "redux-thunk";
const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, storeEnhancers(applyMiddleware(asyncMiddleWare, thunk)));
export default store;
I load data in componentDidMount method in my component :
import React from "react";
import { connect } from "react-redux";
import { getData } from "./js/actions/index";
class Post extends React.Component {
componentDidMount() {
this.props.getData();
}
render () {
console.log(this.props.articles);
return (
<div className='post'>
{this.props.articles.map(article => (
<div className='post'>
{article}
</div>
))}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
articles: state.remoteArticles.slice(0, 10)
};
}
export default connect(
mapStateToProps,
{getData}
)(Post);
If you look into your middleware resolved promise function you'll notice that you are dispatching action of same type (DATA_LOADED) again which causes middleware to process it again.
Take a look at this approach
export function asyncMiddleWare({dispatch}) {
return function(next) {
return function (action) {
if (action.type === DATA_LOAD_REQUEST) {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => {
console.log('---');
console.log('infinite calls');
console.log('---');
dispatch({type:DATA_LOAD_SUCCESS, payload: json});
}, (error) => {
dispatch({type:DATA_LOAD_ERROR, payload: error});
})
}
return next(action);
}
}
}
You should separate your REQUEST, SUCCESS and ERROR calls so when you call each of those actions you don't end up in infinite loop.

React redux api polling every x seconds

I've got this working but i'm after a more 'best practice way'.
its using the https://icanhazdadjoke api to display a random joke that gets updated every x seconds. is there a better way of doing this?
eventually i want to add stop, start, reset functionality and feel this way might not be the best.
Any middleware i can use?
Redux actions
// action types
import axios from 'axios';
export const FETCH_JOKE = 'FETCH_JOKE';
export const FETCH_JOKE_SUCCESS = 'FETCH_JOKE_SUCCESS';
export const FETCH_JOKE_FAILURE = 'FETCH_JOKE_FAILURE';
function fetchJoke() {
return {
type: FETCH_JOKE
};
}
function fetchJokeSuccess(data) {
return {
type: FETCH_JOKE_SUCCESS,
data
};
}
function fetchJokeFail(error) {
return {
type: FETCH_JOKE_FAILURE,
error
};
}
export function fetchJokeCall(){
return function(dispatch){
dispatch(fetchJoke());
return axios.get('https://icanhazdadjoke.com', { headers: { 'Accept': 'application/json' }})
.then(function(result){
dispatch(fetchJokeSuccess(result.data))
})
.catch(error => dispatch(fetchJokeFail(error)));
}
}
Redux reducer
import {combineReducers} from 'redux';
import {FETCH_JOKE, FETCH_JOKE_SUCCESS, FETCH_JOKE_FAILURE} from '../actions';
const defaultStateList = {
isFetching: false,
items:[],
error:{}
};
const joke = (state = defaultStateList, action) => {
switch (action.type){
case FETCH_JOKE:
return {...state, isFetching:true};
case FETCH_JOKE_SUCCESS:
return {...state, isFetching:false, items:action.data};
case FETCH_JOKE_FAILURE:
return {...state, isFetching:false, error:action.data};
default:
return state;
}
};
const rootReducer = combineReducers({
joke
});
export default rootReducer;
Joke component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { fetchJokeCall } from '../actions';
class Joke extends Component {
componentDidMount() {
this.timer = setInterval(()=> this.props.fetchJokeCall(), 1000);
}
componentWillUnmount() {
clearInterval(this.timer)
this.timer = null;
}
render() {
return (
<div>
{this.props.joke.joke}
</div>
);
}
}
Joke.propTypes = {
fetchJokeCall: PropTypes.func,
joke: PropTypes.array.isRequired
};
function mapStateToProps(state) {
return {
joke: state.joke.items,
isfetching: state.joke.isFetching
};
}
export default connect(mapStateToProps, { fetchJokeCall })(Joke);
Redux-Sagas is better and we are using it in our applications as well, this is how you can poll using Redux-Sagas
Just to give you an idea this is how you can do it, You also need to understand how Redux-Sagas work
Action
export const FETCH_JOKE = 'FETCH_JOKE';
export const FETCH_JOKE_SUCCESS = 'FETCH_JOKE_SUCCESS';
export const FETCH_JOKE_FAILURE = 'FETCH_JOKE_FAILURE';
export const START_POLLING = 'START_POLLING';
export const STOP_POLLING = 'STOP_POLLING';
function startPolling() {
return {
type: START_POLLING
};
}
function stopPolling() {
return {
type: STOP_POLLING
};
}
function fetchJoke() {
return {
type: FETCH_JOKE
};
}
function fetchJokeSuccess(data) {
return {
type: FETCH_JOKE_SUCCESS,
data
};
}
function fetchJokeFail(error) {
return {
type: FETCH_JOKE_FAILURE,
error
};
}
Reducer
import {combineReducers} from 'redux';
import {FETCH_JOKE, FETCH_JOKE_SUCCESS, FETCH_JOKE_FAILURE, START_POLLING, STOP_POLLING } from '../actions';
const defaultStateList = {
isFetching: false,
items:[],
error:{},
isPolling: false,
};
const joke = (state = defaultStateList, action) => {
switch (action.type){
case FETCH_JOKE:
return {...state, isFetching:true};
case FETCH_JOKE_SUCCESS:
return {...state, isFetching:false, items:action.data};
case FETCH_JOKE_FAILURE:
return {...state, isFetching:false, error:action.data};
case START_POLLING:
return {...state, isPolling: true};
case STOP_POLLING:
return {...state, isPolling: false};
default:
return state;
}
};
const rootReducer = combineReducers({
joke
});
export default rootReducer;
Sagas
import { call, put, takeEvery, takeLatest, take, race } from 'redux-saga/effects'
import {FETCH_JOKE, FETCH_JOKE_SUCCESS, FETCH_JOKE_FAILURE, START_POLLING, STOP_POLLING } from '../actions';
import axios from 'axios';
function delay(duration) {
const promise = new Promise(resolve => {
setTimeout(() => resolve(true), duration)
})
return promise
}
function* fetchJokes(action) {
while (true) {
try {
const { data } = yield call(() => axios({ url: ENDPOINT }))
yield put({ type: FETCH_JOKE_SUCCESS, data: data })
yield call(delay, 5000)
} catch (e) {
yield put({ type: FETCH_JOKE_FAILURE, message: e.message })
}
}
}
function* watchPollJokesSaga() {
while (true) {
const data = yield take(START_POLLING)
yield race([call(fetchJokes, data), take(STOP_POLLING)])
}
}
export default function* root() {
yield [watchPollJokesSaga()]
}
You can also use Redux-Observable, if you want to get more into this read this article
I've been working on pretty much the same problem, except that I wasn't concerned about starting and stopping the poll. For some reason the while loop kept freezing my app so I dispensed of it and instead set up my saga like this.
import { all, takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';
import { API_CALL_REQUEST, API_CALL_SUCCESS, API_CALL_FAILURE, API_CALL_FETCHED } from
'../actions/giphy';
function apiFetch() {
let randomWord = require('random-words');
let API_ENDPOINT = `https://api.giphy.com/v1/gifs/search?
api_key=MYKEY&q=${randomWord()}&limit=12`;
return axios({
method: "get",
url: API_ENDPOINT
});
}
export function* fetchImages() {
try {
const res = yield call(apiFetch)
const images = yield res.data
yield put({type: API_CALL_SUCCESS, images})
} catch (e) {
yield put({type: API_CALL_FAILURE, e})
console.log('Error fetching giphy data')
}
}
export default function* giphySaga() {
yield all([
takeLatest(API_CALL_REQUEST, fetchImages),
]);
}
Then inside my component I added this.
componentDidMount() {
this.interval = setInterval(() => {
this.props.dispatch({type: 'API_CALL_REQUEST'});
}, 5000);
}
componentWillUnmount() {
clearInterval(this.interval)
}
It's working, but would like some feedback on how this could be possibly improved.
Here's a poor man's way. I don't think it's the best way but it doesn't require any extra library.
Actions
// action types
import axios from 'axios';
export const START_POLLING_JOKE = 'START_POLLING_JOKE';
export const STOP_POLLING_JOKE = 'STOP_POLLING_JOKE';
export const FETCH_JOKE = 'FETCH_JOKE';
export const FETCH_JOKE_SUCCESS = 'FETCH_JOKE_SUCCESS';
export const FETCH_JOKE_FAILURE = 'FETCH_JOKE_FAILURE';
const defaultPollingInterval = 60000
function startPollingJoke(interval = defaultPollingInterval) {
return function (dispatch) {
const fetch = () => dispatch(fetchJoke())
dispatch({
type: START_POLLING_JOKE,
interval,
fetch,
})
}
}
function stopPollingJoke() {
return {
type: STOP_POLLING_JOKE
}
}
function fetchJoke() {
return {
type: FETCH_JOKE
};
}
function fetchJokeSuccess(data) {
return {
type: FETCH_JOKE_SUCCESS,
data
};
}
function fetchJokeFail(error) {
return {
type: FETCH_JOKE_FAILURE,
error
};
}
export function pollJokeCall(interval = defaultPollingInterval) {
return function (dispatch) {
dispatch(fetchJoke())
dispatch(startPollingJoke(interval))
}
}
export function fetchJokeCall() {
return function(dispatch){
dispatch(fetchJoke());
return axios.get('https://icanhazdadjoke.com', { headers: { 'Accept': 'application/json' }})
.then(function(result){
dispatch(fetchJokeSuccess(result.data))
})
.catch(error => dispatch(fetchJokeFail(error)));
}
}
Reducers
import {combineReducers} from 'redux';
import {
START_POLLING_JOKE,
STOP_POLLING_JOKE,
FETCH_JOKE,
FETCH_JOKE_SUCCESS,
FETCH_JOKE_FAILURE,
} from '../actions';
const defaultStateList = {
isFetching: false,
items:[],
error:{},
pollingId: null,
polling: false,
};
const joke = (state = defaultStateList, action) => {
switch (action.type){
case START_POLLING_JOKE:
clearInterval(state.pollingId)
return {
...state,
polling: true,
pollingId: setInterval(action.fetch, action.interval),
}
}
case STOP_POLLING_JOKE:
clearInterval(state.pollingId)
return {...state, polling: false, pollingId: null}
case FETCH_JOKE:
return {...state, isFetching:true};
case FETCH_JOKE_SUCCESS:
return {...state, isFetching:false, items:action.data};
case FETCH_JOKE_FAILURE:
return {...state, isFetching:false, error:action.data};
default:
return state;
}
};
const rootReducer = combineReducers({
joke
});
export default rootReducer;
Component (might have a bug because I'm not used to class components)
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { pollJokeCall, stopPollingJoke } from '../actions';
class Joke extends Component {
componentDidMount() {
this.props.pollJokeCall()
}
componentWillUnmount() {
this.props.stopPollingJoke()
}
render() {
return (
<div>
{this.props.joke.joke}
</div>
);
}
}
Joke.propTypes = {
pollJokeCall: PropTypes.func,
stopPollingJoke: PropTypes.func,
joke: PropTypes.array.isRequired,
};
function mapStateToProps(state) {
return {
joke: state.joke.items,
isfetching: state.joke.isFetching
};
}
export default connect(mapStateToProps, { pollJokeCall, stopPollingJoke })(Joke);
I have made a small (5kb gzipped) helper to create polling based on redux-thunk store. The idea is to have a logic to prevent registering the same polling twice, have callbacks between iterations and more.
https://www.npmjs.com/package/redux-polling-thunk
redux-saga is great and I've been using this with redux. It provides a great api to do things like delay, polling, throttling, race conditions, task cancellations. So using redux-saga, you can add a watcher whcih will keep on pooling
function* pollSagaWorker(action) {
while (true) {
try {
const { data } = yield call(() => axios({ url: ENDPOINT }));
yield put(getDataSuccessAction(data));
yield call(delay, 4000);
} catch (err) {
yield put(getDataFailureAction(err));
}
}
}

How do i properly do a GET request in react-redux?

My goal is to basically do a basic GET request in react-redux. I know how to do it with POST but not with GET because there is no event that is triggering the action.
Heres' the code for action
export function getCourses() {
return (dispatch) => {
return fetch('/courses', {
method: 'get',
headers: { 'Content-Type': 'application/json' },
}).then((response) => {
if (response.ok) {
return response.json().then((json) => {
dispatch({
type: 'GET_COURSES',
courses: json.courses
});
})
}
});
}
}
Where do i trigger this to get the data? in component?
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { getCourses } from '../actions/course';
class Course extends React.Component {
componentDidMount() {
this.props.onGetCourses();
}
allCourses() {
console.log(this.props.onGetCourses());
return this.props.courses.map((course) => {
return(
<li>{ course.name }</li>
);
});
return this.props
}
render() {
return (
<div>
<ul>
{ this.allCourses() }
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
courses: state.course.courses
}
}
const mapDispatchToProps = (dispatch) => {
return {
onGetCourses: () => dispatch(getCourses)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Course);
I tried this but it doesn't work.
Course Reducer
const initialState = {
courses: []
};
export default function course(state= initialState, action) {
switch (action.type) {
case 'GET_COURSES':
return Object.assign({}, state, {
courses: action.courses
})
default:
return state;
}
}
First, onGetCourses: () => dispatch(getCourses) should be changed to onGetCourses: () => dispatch(getCourses()) (you need to actually invoke the action creator).
When it comes to where you should call the action, it is absolutely fine to do it in componentDidMount, as you have done.
In case you did not notice, you have two return's in your allCourses().
I have similar code in my codebase, but I don't use return in front of fetch and response.json() because the function should return action object.

Resources