I'm having problems with setting my state when a ajax call is successfully run. I want to update the state when the ajax process is completed.
The text in the div stays on "Busy" instead of "Done", while in the browser Network Tab, I see the status changing from "pending" to status "200".
import React, { Component } from "react";
import * as ReactDOM from "react-dom";
import { extend } from "lodash";
export class StoreToCheck extends React.Component{
constructor(props){
super(props);
this.state = { ListWithISBN :[],
getISBNS : false };
this.ajaxSuccess = this.ajaxSuccess.bind(this);
}
getISBNSList(){
if(!this.state.getISBNS){
var store_name;
// loop through array to fill store_name variable
var ajaxSuccess = this.ajaxSuccess;
if(store_name != ''){
apex.server.process(
'GET_EBOOKS_FROM_STORE',
{
success:function (data){
// when succesfull update state getISBNS
ajaxSuccess
}
}
);
}
}
}
ajaxSuccess(){
this.setState({"getISBNS":true});
}
componentDidMount(){
this.getISBNSList();
}
render(){
return(
<div>
{this.state.getISBNS ? "Done" : "Busy"}
</div>
)
}
}
You need to call ajaxSuccess method, also instead of storing the correct function reference, you can bind it inplace
getISBNSList(){
if(!this.state.getISBNS){
var store_name;
// loop through array to fill store_name variable
if(store_name != ''){
apex.server.process(
'GET_EBOOKS_FROM_STORE',
{
success: (data) => { // bind here with arrow function
// when succesfull update state getISBNS
this.ajaxSuccess() // call the function
}
}
);
}
}
}
Related
I learn React-Redux and need help understanding why this Component only works on start but not when I press the button.
When debug start the breakpoints in the picture break execution but when I press the button I get this error showed in the picture.
When breakpoints hit I hoower over the {toasts.map(toast => { and the Array size is zero. But when I press button the breakpoints does not even hit
Any ide?
UPDATE
I have this configureStore.js
import { combineReducers } from "redux";
import { createStore, applyMiddleware, compose } from "redux";
import { forbiddenWordsMiddleware } from "../middleware";
import ToastsReducer from '../reducers/ToastsReducer';
import RootReducer from '../reducers/RootReducer';
const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const reducers = {
toastsReducer: ToastsReducer,
rootReducer: RootReducer
};
const reduce = combineReducers({
...reducers,
});
const store = createStore(
reduce,
storeEnhancers(applyMiddleware(forbiddenWordsMiddleware))
);
export default store;
RootReducer.js
import { ADD_ARTICLE } from "../constants/action-types";
import { FOUND_BAD_WORD } from "../constants/action-types";
const initialState = {
articles: []
};
export default function reducer(state = initialState, action) {
if (action.type === ADD_ARTICLE) {
return Object.assign({}, state, {
articles: state.articles.concat(action.payload)
});
}
if (action.type === FOUND_BAD_WORD) {
//return Object.assign({}, state, {
// articles: state.articles.concat(action.payload)
// });
}
return state;
}
ToastsReducer.js
import { ADD_TOAST, REMOVE_TOAST } from "../constants/action-types";
const initialState = {
toastList: []
};
export default function toasts(state = initialState, action) {
const { payload, type } = action;
switch (type) {
case ADD_TOAST:
return [payload, state.toastList];
case REMOVE_TOAST:
return state.toastList.filter(toast => toast.id !== payload);
default:
return state;
}
}
UPDATE
Picture showing RootReducer.jsx and Toasts.jsx when I press button two times,
Toast.js
import PropTypes from "prop-types";
import React, { Component } from "react";
class Toast extends Component {
render() {
return (
<li className="toast" style={{ backgroundColor: this.props.color }}>
<p className="toast__content">
{this.props.text}
</p>
<button className="toast__dismiss" onClick={this.props.onDismissClick}>
x
</button>
</li>
);
}
shouldComponentUpdate() {
return false;
}
}
Toast.propTypes = {
color: PropTypes.string.isRequired,
onDismissClick: PropTypes.func.isRequired,
text: PropTypes.string.isRequired
};
export default Toast;
Please share your reducer code. Most likely, you have not set an initial state for toastList in the reducer or there is an error with toastsReducer.toastList.
Try the following:
Change line 34 to toasts: state.toastsReducer
Comment the lines from 10 to 19 and insert the following to make sure toasts is an array.
console.log(toasts);
console.log(toasts.toastList);
return null;
If both are undefined, then the value returned by the reducer is not right.
In ToastsReducer.js:
Change the following:
case ADD_TOAST:
return [ ...state.toastList, payload]; //<--- Here
When you do return[payload,state.toastList], it appends another array to the toastList.
Run the following to see:
toastList = ['abc'];
// Right way to add an item to an array.
toastList = [...toastList, 'def'];
console.log(toastList);
console.log('-----');
// Adds an array to the array. Incorrect way.
toastList = [toastList, 'ghi'];
console.log(toastList);
---UPDATE---
Change your ADD_TOAST case to:
return { toastList: [...state.toastList, payload] };
and you should be good to go.
Just do check your toasts array contains data,
{toasts && toasts.length > 0 ? toasts.map(toast => {...}) : null}
I have a reactjs component with redux which passes asynchronously props to child component.
In child component I try to catch the data in componentDidMount but somehow does not work either, however the child component is getting rendered.
This is my parent component
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as slidesActions from '../../actions/slidesActions';
import Slider from '../Partials/Slider'
import _ from 'underscore';
class HomePage extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.actions.getSlides()
}
componentWillMount() {
const {slides} = this.props;
}
render() {
const {slides} = this.props;
return (
<div className="homePage">
<Slider columns={1} slides={slides} />
</div>
);
}
}
function mapStateToProps(state) {
return {
slides: state.slides
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(slidesActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
here comes my child component where I try to get passed slides props but is empty
import React from 'react';
import _ from 'underscore';
import Hammer from 'hammerjs';
class Slider extends React.Component {
constructor(props) {
super(props)
this.updatePosition = this.updatePosition.bind(this);
this.next = this.next.bind(this);
this.prev = this.prev.bind(this);
this.state = {
images: [],
slidesLength: null,
currentPosition: 0,
slideTransform: 0,
interval: null
};
}
next() {
const currentPosition = this.updatePosition(this.state.currentPosition - 10);
this.setState({ currentPosition });
}
prev() {
//TODO: work on logic
if( this.state.currentPosition !== 0) {
const currentPosition = this.updatePosition(this.state.currentPosition + 10);
this.setState({currentPosition});
}
}
componentDidMount() {
//here I try set a state variable on slides
let {slides} = this.props
let slidesLength = slides.length
this.setState({slidesLength})
this.hammer = Hammer(this._slider)
this.hammer.on('swipeleft', this.next);
this.hammer.on('swiperight', this.prev);
}
componentWillUnmount() {
this.hammer.off('swipeleft', this.next)
this.hammer.off('swiperight', this.prev)
}
updatePosition(nextPosition) {
const { visibleItems, currentPosition } = this.state;
return nextPosition;
}
render() {
let {slides, columns} = this.props
let {currentPosition} = this.state
let sliderNavigation = null
//TODO: this should go to slides actions
let slider = _.map(slides, function (slide) {
let Background = slide.featured_image_url.full;
if(slide.status === 'publish')
return <div className="slide" id={slide.id} key={slide.id}><div className="Img" style={{ backgroundImage: `url(${Background})` }} data-src={slide.featured_image_url.full}></div></div>
});
if(slides.length > 1 ) {
sliderNavigation = <ul className="slider__navigation">
<li data-slide="prev" className="" onClick={this.prev}>previous</li>
<li data-slide="next" className="" onClick={this.next}>next</li>
</ul>
}
return <div ref={
(el) => this._slider = el
} className="slider-attached"
data-navigation="true"
data-columns={columns}
data-dimensions="auto"
data-slides={slides.length}>
<div className="slides" style={{ transform: `translate(${currentPosition}%, 0px)`, left : 0 }}> {slider} </div>
{sliderNavigation}
</div>
}
}
export default Slider;
and here I have my actions for slider
import * as types from './actionTypes';
import axios from 'axios';
import _ from 'underscore';
//TODO: this should be accessed from DataService
if (process.env.NODE_ENV === 'development') {
var slidesEndPoint = 'http://dev.server/wp-json/wp/v2/slides';
} else {
var slidesEndPoint = 'http://prod.server/wp-json/wp/v2/slides';
}
export function getSlides () {
return dispatch => {
dispatch(setLoadingState()); // Show a loading spinner
axios.get(slidesEndPoint)
.then(function (response) {
dispatch(setSlides(response.data))
dispatch(doneFetchingData(response.data))
})
/*.error((response) => {
dispatch(showError(response.data))
})*/
}
}
function setSlides(data) {
return {
type: types.SLIDES_SUCCESS,
slides: data
}
}
function setLoadingState() {
return {
type: types.SHOW_SPINNER,
loaded: false
}
}
function doneFetchingData(data) {
return {
type: types.HIDE_SPINNER,
loaded: true,
slides: data
}
}
function showError() {
return {
type: types.SHOW_ERROR,
loaded: false,
error: 'error'
}
}
Reason is, componentDidMount will get called only once, just after the initial rendering, since you are fetching the data asynchronously so before you get the data Slider component will get rendered.
So You need to use componentwillreceiveprops lifecycle method.
componentDidMount:
componentDidMount() is invoked immediately after a component is
mounted. Initialization that requires DOM nodes should go here. If you
need to load data from a remote endpoint, this is a good place to
instantiate the network request. Setting state in this method will
trigger a re-rendering.
componentWillReceiveProps:
componentWillReceiveProps() is invoked before a mounted component
receives new props. If you need to update the state in response to
prop changes (for example, to reset it), you may compare this.props
and nextProps and perform state transitions using this.setState() in
this method.
Write it like this:
componentWillReceiveProps(nextProps){
if(nextProps.slides){
let {slides} = nextProps.props
let slidesLength = slides.length;
this.hammer = Hammer(this._slider)
this.hammer.on('swipeleft', this.next);
this.hammer.on('swiperight', this.prev);
this.setState({slidesLength})
}
}
As far as I understand, you are doing an axios call to fetch the data and then set it in the reducer which you are returning later. Also initially reducer data is empty . Now since componentDidMount is called only once, and initially no data may have been there you are not seeing any values. Use a componentWillReceiveProps function
componentWillReceiveProps(nextProps) {
//here I try set a state variable on slides
let {slides} = nextProps
let slidesLength = slides.length
this.setState({slidesLength})
this.hammer = Hammer(this._slider)
this.hammer.on('swipeleft', this.next);
this.hammer.on('swiperight', this.prev);
}
So I am learning React-Redux. I am trying to find a way to load a value from the database first on load instead of just starting from 0. I have written an action that will hit an endpoint on my node file and pull from my mongo database. This works. However the action never seems to reach the reducer to actually update the store. Can someone explain to me the right way to make sure this action is store aware.
Here is the code for the action. Note the console.log with the number prints out what I want. I just never see the logs in the reducer that it was even ever reached.
export function setFooClicks(){
console.log("in the set foo clicks action")
var number = 0;
//return function(dispatch){
//console.log("in the return function")
return axios.get('/clicks').then(result => {
number = result.data
console.log("The number of clicks is", number)
//return number
return{
type: types.SETFOOCLICKS,
totalFoo: result.data
}
}).catch((error) => {
return console.log(error);
})
//}
}
I am trying to grab it in the top level container at the moment so here is the code for that.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Foo from '../components/Foo'
import { incrementFoo, setFooClicks } from '../actions'
class FooContainer extends Component {
componentDidMount(){
setFooClicks();
}
render() {
return (
<div>
<Foo incrementFooAction={() => this.props.incrementFoo()} totalFoo={this.props.totalFoo}/>
</div>
)
}
}
function mapStateToProps(state) {
return {
totalFoo: state.foo.totalFoo
}
}
export default connect(mapStateToProps, { incrementFoo,setFooClicks })(FooContainer)
The normal incrementFoo action works but trying to add the setFooClicks action into the component as well doesn't. Lastly here is the code to the reducer funciton. All I did was add a case to the switch block.
export default function incrementFoo(state = initialState, action) {
console.log("I am in the foo reducer")
console.log(action.type)
switch (action.type) {
case INCREMENT:
console.log(state.totalFoo);
return {
...state,
totalFoo: state.totalFoo + 1
}
case SETFOOCLICKS:
console.log("in the SETFOOCLICKS reducer")
return{
...state,
totalFoo: action.totalFoo
}
default:
return state
}
}
I use react/redux to create an app.
I've a custom action creator to make an async request (I use redux-thunk).
export function loginAttempt(userData) {
return dispatch => {
let formData = new FormData();
formData.append('username', userData.username);
formData.append('password', userData.password);
fetch('https://api.t411.ch/auth', {
method: 'POST',
body: formData
}).then(response => {
if (response.status !== 200) {
const error = new Error(response.statusText);
error.respone = response;
dispatch(loginError(error));
throw error;
}
return response.json();
}).then(data => {
dispatch(loginSuccess(data));
});
}
In my component, I use bindActionCreators to bind this method with dispatch :
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SearchBar from './SearchBar';
import TorrentLayout from './TorrentLayout';
import * as LoginActions from '../actions/login'; // <---- it's where the code above is located
import * as SearchActions from '../actions/search';
function mapStateToProps(state) {
return {
login: state.login,
searching: state.searching
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({...LoginActions, ...SearchActions}, dispatch);
}
#connect(mapStateToProps, mapDispatchToProps)
export default class Home extends Component {
constructor(props) {
super(props);
console.log('should be a promise');
let foobar = this.props.loginAttempt({username: 'username', password:'password'});
console.log(foobar); // <------ undefined
// that I want to do
this.props.loginAttempt({username: 'username', password:'password'}).then(() => {
this.props.search(this.props.login.token, "mysearch");
}
}
render() {
return (
<div>
<div>
<SearchBar {...this.props} />
<TorrentLayout {...this.props}/>
</div>
</div>
);
}
}
I would like to apply 'then' to my action creator already bound to dispatch.
Thanks
You need to return fetch() inside your arrow function inside loginAttempt. Like so:
export function loginAttempt(userData) {
return dispatch => {
return fetch('https://api.t411.ch/auth', {
method: 'POST',
body: formData
}).then(...);
}
Basically when you call your binded action creator the arrow functions gets executed but it doesn't have a return value.
For me, I'm doing all the logic inside the dispatcher, so I passed to it a done callback.
In my component, I'm calling the action login as follow
login(values, setErrors, (user) => {
console.log('done:', user)
})
then on my action, I do all the async calls, then call done(data) at the end
export const login = (form: ILoginForm, setErrors, done) => {
return async (dispatch: Dispatch<Action>) => {
// ....
done(data)
}
Its a common problem, React Native trying to render before the values have been fetched from AsyncStorage. I've seen solutions for this in several places but for some reason it just doesn't work at all for me. Maybe its because I'm using React Native 25.1? It just gets stuck on 'Loading...' indefinitely. If I run a console log on render to show isLoading (without the if method) it returns false and then true so theoretically it should be working. But with the if method enabled its stuck on 'Loading' forever and also the log only returns false.
import React, { Component } from 'react';
import {
Text,
View,
AsyncStorage
} from 'react-native';
class MainPage extends Component {
constructor(props: Object): void {
super();
this.state = {
isLoading: false,
};
}
componentWillMount() {
AsyncStorage.getItem('accessToken').then((token) => {
this.setState({
isLoading: false
});
});
}
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
// this is the content you want to show after the promise has resolved
return <View/>;
}
});
Hey try this...
import React, { Component } from 'react';
import {
Text,
View,
AsyncStorage
} from 'react-native';
class MainPage extends Component {
constructor(props: Object): void {
super(props);
this.state = {
isLoading: false,
};
}
componentWillMount() {
AsyncStorage.getItem('accessToken').then((token) => {
this.setState({
isLoading: false
});
});
}
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
// this is the content you want to show after the promise has resolved
return <View/>;
}
}
Let me know if you need more clarifications...