React Native: Possible Unhandled Promise Rejection (id: 0) - javascript

so i'm trying to learn more about Redux through React-Native.
i'm trying to issue a HTTPS request with Axios to pull data from a web-server. everything runs fine, i console log the action and the payload is the data i need. but it still throws a 'Cannot read property 'data' of null' TypeError.
the following is my code:
import React, { Component } from 'react';
import ReduxThunk from 'redux-thunk';
import { StackNavigator } from 'react-navigation';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from '../reducers';
import ReduxTestObj from '../components/ReduxTestObj';
export default class ReduxTest extends Component {
render() {
return (
<Provider store={createStore(reducers, {}, applyMiddleware(ReduxThunk))}>
<ReduxTestObj />
</Provider>
);
}
}
Here is the ReduxTestObj
import React, { Component } from 'react';
import _ from 'lodash';
import { View } from 'react-native';
import { connect } from 'react-redux';
import DevBanner from './DevBanner';
import Header from './Header';
import { actionCreator } from '../actions';
class ReduxTestObj extends Component {
componentWillMount() {
this.props.actionCreator('urlIWantToGoTo');
}
getBannerText() {
if (this.props.loading) {
return 'PULLING DATA. GIVE ME A SECOND';
}
const rObj = _.map(this.state.data[1].recipient_list);
const rName = [];
for (let i = 0; i < rObj.length; i++) {
rName[i] = rObj[i].team_key.substring(3);
}
const winnerMSG = `Teams ${rName[0]}, ${rName[1]}, ${rName[2]}, ${rName[3]} Won`;
return winnerMSG;
}
render() {
return (
<View>
<Header
text={'Redux Testing'}
/>
<DevBanner
message={this.getBannerText()}
/>
</View>
);
}
}
const mapStateToProps = state => {
return {
data: state.tba.data,
loading: state.tba.loading
};
};
export default connect(mapStateToProps, { actionCreator })(ReduxTestObj);
Here is the Action Creator
import axios from 'axios';
import { TBA_PULL } from './Types';
export const actionCreator = (url) => {
return (dispatch) => {
axios({
method: 'get',
url,
responseType: 'json',
headers: {
'Auth-Key':
'Hidden For Obvious Reasons'
},
baseURL: 'theBaseUrlOfTheWebsite'
}).then(response => {
dispatch({ type: TBA_PULL, payload: response.data });
});
};
};
And Here is the Reducer
import { TBA_PULL } from '../actions/Types';
const INITIAL_STATE = { data: [], loading: true };
export default (state = INITIAL_STATE, action) => {
console.log(action);
switch (action.type) {
case TBA_PULL:
return { ...state, loading: false, data: action.payload };
default:
return state;
}
};
As stated above, the console.log(action) prints out and the data it has is correct. yet it continues to throw the following error:
Error1
I've tried changing things around, googling, searching, gutting out the Action Reducer to make it as basic as possible by just returning a string. and it refuses to work.
Has anyone run into an issue similar to this or know how to fix it?
Thank you for your time.
EDIT: i also console logged 'this' as the first line of getBannerText() in ReduxTestObj and it returned successfully this.props.data as the data i want and this.props.loading as false. Yet it still throws the same error.

Welp. I guess i was just making a mistake.
i was calling This.state.data instead of this.props.data in getBannerText().
that solved the issue.

Related

How to dispatch an action from inside getInitialProps?

I am trying to implement Redux in a Next.js app and have problems getting the dispatch function to work in getInitialProps. The store is returned as undefined for some reason that I cannot figure out. I am using next-redux-wrapper. I have followed the documentation on next-redux-wrapper GitHub page but somewhere on the way it goes wrong. I know the code is working - I used axios to directly fetch the artPieces and then it worked just fine but I want to use Redux instead. I am changing an react/express.js app to a Next.js app where I will use the API for the basic server operations needed. This is just a small blog app.
Here is my store.js:
import { createStore } from 'redux';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';
// create your reducer
const reducer = (state = { tick: 'init' }, action) => {
switch (action.type) {
case HYDRATE:
return { ...state, ...action.payload };
case 'TICK':
return { ...state, tick: action.payload };
default:
return state;
}
};
// create a makeStore function
const makeStore = (context) => createStore(reducer);
// export an assembled wrapper
export const wrapper = createWrapper(makeStore, { debug: true });
And here is the _app.js:
import './styles/globals.css';
import { wrapper } from '../store';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default wrapper.withRedux(MyApp);
And finally here is where it does not work. Trying to call dispatch on the context to a sub component to _app.js:
import React from 'react';
import { ArtPiecesContainer } from './../components/ArtPiecesContainer';
import { useDispatch } from 'react-redux';
import axios from 'axios';
import { getArtPieces } from '../reducers';
const Art = ({ data, error }) => {
return (
<>
<ArtPiecesContainer artPieces={data} />
</>
);
};
export default Art;
Art.getInitialProps = async ({ ctx }) => {
await ctx.dispatch(getArtPieces());
console.log('DATA FROM GETARTPIECES', data);
return { data: ctx.getState() };
};
This should probably work with "next-redux-wrapper": "^7.0.5"
_app.js
import { wrapper } from '../store'
import React from 'react';
import App from 'next/app';
class MyApp extends App {
static getInitialProps = wrapper.getInitialAppProps(store => async ({Component, ctx}) => {
return {
pageProps: {
// Call page-level getInitialProps
// DON'T FORGET TO PROVIDE STORE TO PAGE
...(Component.getInitialProps ? await Component.getInitialProps({...ctx, store}) : {}),
// Some custom thing for all pages
pathname: ctx.pathname,
},
};
});
render() {
const {Component, pageProps} = this.props;
return (
<Component {...pageProps} />
);
}
}
export default wrapper.withRedux(MyApp);
and Index.js
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { END } from 'redux-saga'
import { wrapper } from '../store'
import { loadData, startClock, tickClock } from '../actions'
import Page from '../components/page'
const Index = () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(startClock())
}, [dispatch])
return <Page title="Index Page" linkTo="/other" NavigateTo="Other Page" />
}
Index.getInitialProps = wrapper.getInitialPageProps(store => async (props) => {
store.dispatch(tickClock(false))
if (!store.getState().placeholderData) {
store.dispatch(loadData())
store.dispatch(END)
}
await store.sagaTask.toPromise()
});
export default Index
For the rest of the code you can refer to nextjs/examples/with-redux-saga, but now that I'm posting this answer they're using the older version on next-redux-wrapper ( version 6 ).

Redux saga not calling the API

I am trying to use redux-saga to call my API and passing it a parameter. I am using redux-logger and console.log() to debug. But it seems that my saga doesn't go call the API for some reason.
Here is the console log of the states... as you can see the apiMsg doesnt change, however I have it change for each action.
I think I am going wrong somewhere in the actions, reducer or the component. Or else I am calling the API wrong in the Saga.
This is my code
api.js
import axios from 'axios';
export function getPostApi(postId){
return axios.get(
`https://jsonplaceholder.typicode.com/posts/${postId}`
).then(
response => {
return response;
}
).catch(
err => {throw err;}
);
}
my store
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga'
import {createLogger} from 'redux-logger';
import rootReducer from '../Reducers';
export default function configureStore(initialState) {
const sagaMiddleware = createSagaMiddleware();
const logger = createLogger();
return {
...createStore(rootReducer, initialState, applyMiddleware(sagaMiddleware, logger)),
runSaga: sagaMiddleware.run
}
}
the saga
import {call, put, takeEvery} from 'redux-saga/effects';
import * as service from '../Services/api';
import * as actions from '../Actions';
import * as types from '../actions/actionTypes';
export function* fetchPost(action){
try{
yield put(actions.apiRequest());
const [post] = yield [call(service.getPostApi, action.postId)];
yield put(actions.apiRequestSucceeded(post));
} catch(e){
yield put(actions.apiRequestFailed());
}
}
export function* watchApiRequest() {
yield takeEvery(types.FETCH_POST, fetchPost);
}
actions
import * as types from './actionTypes';
export const fetchPost = (postId) => ({
type: types.FETCH_POST,
postId,
});
export const apiRequest = () => {
return {
type: types.API_REQUEST
}
}
export const apiRequestSucceeded = (post) => {
return {
type: types.API_REQUEST_SUCCEEDED,
post
}
}
export const apiRequestFailed = () => {
return {
type: types.API_REQUEST_FAILED
}
}
reducer
import * as types from '../actions/actionTypes';
const initialState = {
apiMsg: '',
postId: 1,
fetching: false,
post: null
};
export default function getPostData(state = initialState, action) {
switch (action.type) {
case types.API_REQUEST:
return {
...state,
apiMsg: 'API call request!',
fetching: true
}
case types.API_REQUEST_SUCCEEDED:
return {
...state,
apiMsg: 'API called succeeded!',
fetching: false,
postId: action.post.id,
post: action.title
};
case types.API_REQUEST_FAILED:
return {
...state,
apiMsg: 'API called failed!',
fetching: false,
};
default:
return state;
}
}
the component page
import React, { Component } from 'react';
import { View, Text} from 'react-native';
import { connect } from 'react-redux';
import {fetchPost} from './Actions/apiTesterActions';
class TestPage extends Component {
constructor() {
super();
}
componentDidMount() {
this.props.fetchPost(1)
}
render() {
const { postId, fetching, post } = this.props;
console.log('Test page props', postId, fetching, post);
return (
<View>
<Text>Test Page Works! </Text>
</View>
)
}
}
const mapStateToProps = (state) => {
return {
postId: state.getPostData.postId,
fetching: state.getPostData.fetching,
post: state.getPostData.post
}
};
export default connect(mapStateToProps, {fetchPost})(TestPage);
I am still learning Redux, and now redux-saga, so I don't fully understand the structure/hierarchy, but I am learning and any advice is helpful. Thank you
EDIT:
I am using this redux saga api call example as a guide.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import configureStore from './ReduxTest/Store/configureStore';
import rootSaga from './ReduxTest/sagas';
const store = configureStore();
store.runSaga(rootSaga)
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
registerServiceWorker();
saga/index.js
import {fork, all} from 'redux-saga/effects';
import {watchApiRequest} from './apiTester';
export default function* rootSaga() {
yield all [
fork(watchApiRequest)
]
}
After some time with a lot of debugging, I have figured the problem.
When I first started creating the application, I got the following error...
[...effects] has been deprecated in favor of all([...effects]), please update your code
As the yield all [...] was deprecated, I changed my code without taking it into consideration, I was happy the error went, but didn't realize how much of an impact it would have on my application.
(wrong) saga/index.js
import {fork, all} from 'redux-saga/effects';
import {watchApiRequest} from './apiTester';
export default function* rootSaga() {
yield all [
fork(watchApiRequest)
]
}
(right) saga/index.js
import {fork, all} from 'redux-saga/effects';
import {watchApiRequest} from './apiTester';
export default function* rootSaga() {
yield all ([
fork(watchApiRequest)
])
}
As You can see it needed to be wrapped in brackets yield all ([...])
You will get the deprecated error but your code will still work. I am unsure how to fix the deprecated error.
If someone knows how to get rid of the deprecated error than that would great.

Async API Call, Redux React-Native

I have recently started to learn React-Native and I am trying to implement Redux to manage the state of my app.
As I have experience with React JS I implemented the state manage Redux the same way I would usually do with React JS. Everything seems to work except the async api call. The props in store change but it does not change in component props.
Here is how I set my redux store
import { createStore, compose, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import reducer from './reducers';
//create initial state
const initialState = {};
//create a variable that holds all the middleware
const middleware = [thunk, logger];
//create the store
const store = createStore(
reducer,
initialState,
compose(
applyMiddleware(...middleware)
)
);
export default store;
My reducer component
import { FETCH_REQUEST_BEGIN, FETCH_REQUEST_FAILED, DATA_FETCHED} from '../constants';
const initialState = {
movieResults: null,
fetching : false,
failed : false
}
export default (state = initialState, actions)=>{
switch(actions.type){
case FETCH_REQUEST_BEGIN:
return {
...state,
fetching : true
};
case DATA_FETCHED :
return {
...state,
movieResults : actions.payload,
fetchin : false
}
case FETCH_REQUEST_FAILED:
return {
...state,
failed : true
};
default :
return state;
}
}
This is the root reducer
import { combineReducers } from 'redux';
import movieReducer from './movieReducer';
export default combineReducers({
movie : movieReducer
});
action component
import axios from 'axios';
import { FETCH_REQUEST_BEGIN, FETCH_REQUEST_FAILED } from '../constants';
const apiRequest = (url, type) => {
return dispatch => {
dispatch({
type : FETCH_REQUEST_BEGIN
});
axios.get(url)
.then((results) => {
dispatch({
type : type,
payload : results.data
});
}).catch((error) => {
dispatch({
type : FETCH_REQUEST_FAILED,
payload : error
});
});
}
}
export default apiRequest;
Main component
import React, { Component } from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';
import { API, DATA_FETCHED } from '../constants';
import { apiRequest } from '../actions';
import { connect } from 'react-redux';
class Home extends Component {
componentWillMount() {
const discoverUrlMovies =`https://jsonplaceholder.typicode.com/posts`;
this.fetchData(discoverUrlMovies, DATA_FETCHED);
}
fetchData = (url, type) => {
this.props.apiRequest(url, type);
}
shouldComponentUpdate(nextProps, prevProps){
return nextProps != prevProps
}
render() {
const { movie } = this.props;
//console out the props
console.log('this.props', this.props);
let displayMovies;
if(movie === undefined || movie === null ){
displayMovies = <ActivityIndicator size = 'large' color = '#121222'/>
}else {
displayMovies = <Text>Working</Text>
}
return (
<View style = {{flex: 1}}>
<Text>Home</Text>
{
//display result
displayMovies
}
</View>
);
}
}
const mapStateToProps = (state) => {
return {
movie : state.movieResults
}
}
export default connect(mapStateToProps, { apiRequest })(Home);
What am I missing / doing wrong?
You need to define your mapStateToProps func as
movie : state.movie.movieResults
since you're combining them as
export default combineReducers({
movie : movieReducer
});

Redux-Saga somehow reducer updates without going through the saga

I am new to the saga world. Although I have worked with thunk on react-native territory, I am very confused at the moment. I am trying to get the skeleton of my project going which I expect to get very large soon. With that in mind, I am trying to separate the logic into multiple files.
I have gotten the reducer to fire except it is not the way I want. I am not sure how it is even happening. My saga does not fire but my state updates. I see the console log from my reducer but nothing from the saga watcher function. What should I change?
Index.js
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { Provider } from 'react-redux'
import reducer from './reducers'
import rootSaga from './sagas'
import App from './App'
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(rootSaga)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("etlRootDiv"),
);
App.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import FileExtensionSelector from './components/FileExtensionSelector'
import { setFileExtension } from './actions'
class App extends Component {
constructor(props) {
super(props)
}
handleTypeSelect() {
console.log('handle more click');
this.props.setFileExtension('zip');
console.log(this.props);
}
componentWillReceiveProps(nextProps){
console.log(nextProps);
}
render() {
return (
<div>
<FileExtensionSelector onFileTypeSelect={this.handleTypeSelect.bind(this)} />
<div>{this.props.fileType} ...asdasd</div>
</div>
)
}
}
const mapStateToProps = ({ metaState }) => {
const { fileType } = metaState;
return { fileType };
};
const mapDispatchToProps = (dispatch) => ({
setFileExtension(ext) {
dispatch(setFileExtension(ext))
}
})
export default connect(mapStateToProps, mapDispatchToProps)(App)
reducers/index.js
import { combineReducers } from 'redux';
import metaState from './MetaStateReducer';
const rootReducer = combineReducers({
metaState,
})
export default rootReducer
reducers/metastatereducer.js
const INITIAL_STATE = {
fileType: null,
hasHeader: false,
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case 'SET_FILE_EXTENSION':
console.log('/// in set file reducer ///');
console.log(action);
// console.log({ ...state, ...INITIAL_STATE, fileType: action.payload });
return { ...state,...INITIAL_STATE, fileType: action.payload };
default:
return state;
}
}
actions/metaStateActions.js
function action(type, payload = {}) {
return { type, ...payload }
}
export const SET_FILE_EXTENSION = "SET_FILE_EXTENSION";
export const setFileExtension = (extension) => action( SET_FILE_EXTENSION, { payload: extension });
actions/index.js
export { setFileExtension, SET_FILE_EXTENSION } from './metaDataActions';
sagas/metastatesagas.js
import { take, put } from 'redux-saga/effects'
import { SET_FILE_EXTENSION } from '../actions';
function* watchFileExtension(ext) {
console.log(' --- in watch file ext ---');
const { extension } = yield take(SET_FILE_EXTENSION)
console.log(`set extension is ${extension}`);
// yield put({ type: 'SET_FILE_EXTENSION', payload: ext });
}
export const metaStateSagas = [
take("SET_FILE_EXTENSION", watchFileExtension),
]
sagas/index
import { all } from 'redux-saga/effects'
import { metaStateSagas } from './MetaStateSagas';
export default function* rootSaga() {
yield all([
...metaStateSagas,
])
}
redux-saga always passes an action along to the store before attempting to process itself. So, the reducers will always run before any saga behavior executes.
I think the error is that your metaStateSagas array needs to use takeEvery, not take, but I'm not entirely sure. Try that and see if it fixes things.

Handling api calls in Redux with Axios

Good evening everybody!
I'm a total beginner in React and Redux so please bear with me if this sounds totally stupid. I'm trying to learn how I can perform some API calls in Redux and it's not going all to well. When I console log the request from the action creator the promise value is always "undefined" so I'm not sure if I'm doing this correctly.
My goal is to grab the information from the data inside the payload object and display them inside the component. I've been trying to get this to work for the past days and I'm totally lost.
I'm using Axios for and redux-promise to handle the call.
Any help will be greatly appreciated.
Here's the output from the console.
Action Creator
import axios from 'axios';
export const FETCH_FLIGHT = 'FETCH_FLIGHT';
export function getAllFlights() {
const request = axios.get('http://localhost:3000/flug');
console.log(request);
return {
type: FETCH_FLIGHT,
payload: request
};
}
Reducer
import { FETCH_FLIGHT } from '../actions/index';
export default function(state = [], action) {
switch (action.type) {
case FETCH_FLIGHT:
console.log(action)
return [ action.payload.data, ...state ]
}
return state;
}
Component
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getAllFlights } from '../actions/index';
import Destinations from './Destinations';
class App extends Component {
componentWillMount(){
this.props.selectFlight();
}
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
</div>
);
}
function mapStateToProps(state) {
return {
dest: state.icelandair
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ selectFlight: getAllFlights }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
axios is the promise so you need to use then to get your result. You should request your api in a separate file and call your action when the result comes back.
//WebAPIUtil.js
axios.get('http://localhost:3000/flug')
.then(function(result){
YourAction.getAllFlights(result)
});
In your action file will be like this :
export function getAllFlights(request) {
console.log(request);
return {
type: FETCH_FLIGHT,
payload: request
};
}
You can do this with thunk. https://github.com/gaearon/redux-thunk
You can dispatch an action in your then and it will update state when it gets a response from the axios call.
export function someFunction() {
return(dispatch) => {
axios.get(URL)
.then((response) => {dispatch(YourAction(response));})
.catch((response) => {return Promise.reject(response);});
};
}
I also think the best way to do this is by redux-axios-middleware. The setup can be a bit tricky as your store should be configured in a similar way:
import { createStore, applyMiddleware } from 'redux';
import axiosMiddleware from 'redux-axios-middleware';
import axios from 'axios';
import rootReducer from '../reducers';
const configureStore = () => {
return createStore(
rootReducer,
applyMiddleware(axiosMiddleware(axios))
);
}
const store = configureStore();
And your action creators now look like this:
import './axios' // that's your axios.js file, not the library
export const FETCH_FLIGHT = 'FETCH_FLIGHT';
export const getAllFlights = () => {
return {
type: FETCH_FLIGHT,
payload: {
request: {
method: 'post', // or get
url:'http://localhost:3000/flug'
}
}
}
}
The best way to solve this is by adding redux middlewares http://redux.js.org/docs/advanced/Middleware.html for handling all api requests.
https://github.com/svrcekmichal/redux-axios-middleware is a plug and play middleware you can make use of.
I took care of this task like so:
import axios from 'axios';
export const receiveTreeData = data => ({
type: 'RECEIVE_TREE_DATA', data,
})
export const treeRequestFailed = (err) => ({
type: 'TREE_DATA_REQUEST_FAILED', err,
})
export const fetchTreeData = () => {
return dispatch => {
axios.get(config.endpoint + 'tree')
.then(res => dispatch(receiveTreeData(res.data)))
.catch(err => dispatch(treeRequestFailed(err)))
}
}

Categories