I'm rendering high-order component, say Application and I need to fetch some data from server, before it's rendered. What I do, in constructor of Application I issue loadApplicationState() action, that performs server call and prepares initial state.
Some simplified code,
class Application extends Component {
constructor(props) {
super(props);
const { dispatch } = this.props;
dispatch(loadApplicationState());
}
render() {
const { stateLoaded } = this.props.state;
render (
<div>
{ stateLoaded ? renderApp() : renderProgress() }
</div>
)
}
}
function loadApplicationState() {
return (dispatch) => {
// fetch data and once ready,
applicationStateLoaded(data);
}
}
I've tried that on practice, it works fine. But not sure is this a right approach? Especially using a constructor for such purposes.
We run this in componentDidMount, and then test for an $isLoading flag in our Redux state, rendering either a loading indicator or the actual UI. Something like so:
import React, { Component } from 'react';
const mapStateToProps = (state) => ({
$isLoading: state.initialState.$isLoading
})
const mapDispatchToProps = (dispatch) => ({
loadApplicationState(){ dispatch(loadApplicationState()); }
})
export class Application extends Component {
componentDidMount(){
this.props.loadApplicationState();
}
render(){
const {
$isLoading
} = this.props;
{$isLoading ? (<Loader />) : <ActualApplication />}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Application)
Related
I want my component to fetch an array of objects from the server. Each object is a message with author, body and date. I then want to render these messages in my react component.
My react component currently fetches data from the server before mounting. It will then store this message list in the redux state.|
I'm sure there's a better way of writing this code.
1. Can I place the fetch request in either the Action or Reducer file?
2. Can I write a function in the component to make the async call?
import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// Actions
import { fetchMessages } from '../actions/actions_index.js';
class MessageList extends Component {
constructor(props) {
super(props)
}
componentWillMount() {
fetch('https://wagon-chat.herokuapp.com/general/messages')
.then(response => response.json(),
error => console.log('An error occured receiving messages', error))
.then((data) => {
this.props.fetchMessages(data.messages);
});
}
render() {
return (
<div className="message-list">
{this.props.messageList.map( (message, index) => { return <Message key={index} message={message}/> })}
</div>
)
}
}
function mapStateToProps(state) {
return {
messageList: state.messageList
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{ fetchMessages: fetchMessages },
dispatch
)
}
export default connect(mapStateToProps, mapDispatchToProps)(MessageList);
Can I place the fetch request in either the Action or Reducer file?
The fetch request should be placed in action creator. Where the retrieved data will be dispatched to reducer later to manipulate the data, and lastly update the store to show on UI. Here's simple flow for most of react-redux app.
UI -> Action creator (calling request, saga etc..) -> reducer -> store -> UI
Can I write a function in the component to make the async call?
Yes, this should be called action creator, and you can see actions.js below for more reference.
I think you can safely follow this sample pattern where most tutorials out there apply. I'm assuming all files listed here are in the same directory.
constant.js
const MESSAGE_FETCH__SUCCESS = 'MESSAGE/FETCH__SUCCESS'
const MESSAGE_FETCH__ERROR = 'MESSAGE/FETCH__ERROR'
export {
MESSAGE_FETCH__SUCCESS,
MESSAGE_FETCH__ERROR
}
actions.js
import {
MESSAGE_FETCH__SUCCESS,
MESSAGE_FETCH__ERROR
} from './constant';
const fetchMessageError = () => ({
type: MESSAGE_FETCH__ERROR
})
const fetchMessageSuccess = data => ({
type: MESSAGE_FETCH__SUCCESS,
payload: data
})
const fetchMessages = () => {
const data = fetch(...);
// if error
if (data.error)
fetchMessageError();
else fetchMessageSuccess(data.data);
}
export {
fetchMessages
}
reducers.js
import {
MESSAGE_FETCH__SUCCESS,
MESSAGE_FETCH__ERROR
} from './constant';
const INIT_STATE = {
messageList: []
}
export default function( state = INIT_STATE, action ) {
switch(action.type) {
case MESSAGE_FETCH__SUCCESS:
return {
...state,
messageList: action.payload
}
case MESSAGE_FETCH__ERROR:
// Do whatever you want here for an error case
return {
...state
}
default:
return state;
}
}
index.js
Please read the comment I noted
import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { connect } from 'react-redux';
// Actions
import { fetchMessages } from './actions';
class MessageList extends Component {
/* If you don't do anything in the constructor, it's okay to remove calling `constructor(props)`
*/
//constructor(props) {
// super(props)
//}
// I usually put this async call in `componentDidMount` method
componentWillMount() {
this.props.fetchMessage();
}
render() {
return (
<div className="message-list">
{
/* Each message should have an unique id so they can be used
for `key` index. Do not use `index` as an value to `key`.
See this useful link for more reference: https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js
*/
this.props.messageList.map( message => <Message key={message.id} message={message}/> )
}
</div>
)
}
}
function mapStateToProps(state) {
return {
messageList: state.messageList
}
}
export default connect(mapStateToProps, {
fetchMessages
})(MessageList);
You could use redux-thunk in an action called getMessages.
So:
(The double arrow func, is to return an action, see redux-thunk)
const getMessages = ()=>(dispatch, getState)=>{
fetch('https://wagon-chat.herokuapp.com/general/messages')
.then(response => response.json(),
error => dispatch(['error', error]))
.then((data) => {
dispatch(data);
})
}
Then you've successfully reduced your component to:
componentWillMount(){
this.props.getMessages()
}
I think #Duc_Hong answered the question.
And in my opinion, I suggest using the side-effect middle-ware to make AJAX call more structured, so that we could handle more complicated scenarios (e.g. cancel the ajax request, multiple request in the same time) and make it more testable.
Here's the code snippet using Redux Saga
// Actions.js
const FOO_FETCH_START = 'FOO\FETCH_START'
function action(type, payload={}) {
return {type, payload};
}
export const startFetch = () => action{FOO_FETCH_START, payload);
// reducer.js
export const foo = (state = {status: 'loading'}, action) => {
switch (action.type) {
case FOO_FETCH_STARTED: {
return _.assign({}, state, {status: 'start fetching', foo: null});
}
case FOO_FETCH_SUCCESS: {
return _.assign({}, state, {status: 'success', foo: action.data});
}
......
}
};
Can I place the fetch request in either the Action or Reducer file?
// Saga.js, I put the ajax call (fetch, axios whatever you want) here.
export function* fetchFoo() {
const response = yield call(fetch, url);
yield put({type: FOO_FETCH_SUCCESS, reponse.data});
}
// This function will be used in `rootSaga()`, it's a listener for the action FOO_FETCH_START
export function* fooSagas() {
yield takeEvery(FOO_FETCH_START, fetchFoo);
}
Can I write a function in the component to make the async call?
// React component, I trigger the fetch by an action creation in componentDidMount
class Foo extends React.Component {
componentDidMount() {
this.props.startFetch();
}
render() {
<div>
{this.props.foo.data ? this.props.foo.data : 'Loading....'}
<div>
}
}
const mapStateToProps = (state) => ({foo: state.foo});
const mapDispatchToProps = { startFetch }
export default connect(mapStateToProps, mapDispatchToProps) (Foo);
//client.js, link up saga, redux, and React Component
const render = App => {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
combinedReducers,
initialState,
composeEnhancers(applyMiddleware(sagaMiddleware))
);
store.runSaga(rootSaga);
return ReactDOM.hydrate(
<ReduxProvider store={store}>
<BrowserRouter><AppContainer><App/></AppContainer></BrowserRouter>
</ReduxProvider>,
document.getElementById('root')
);
}
I need to change the "global" state of Redux (I believe it's called storage). This is my code:
reducer
export const user = (state = {}, action) => {
console.log(4);
console.log(action.type)
console.log(action.payload)
switch (action.type) {
case C.SET_USER:
console.log(action.payload);
return action.payload;
case C.CLEAR_USER:
return action.payload;
default:
return state;
}
};
Action:
export const setUser = (user = {}) => {
console.log(user);
return {
type: C.SET_USER,
payload: user,
}
};
Calling the action:
const user = {test:true};
setUser(this.state.user);
But if I run this code, it fails and doesn't call the reducer. It calls the action, but not the reducer. What am I missing?
My current app.js code:
export default class App extends Component {
constructor(p) {
super(p);
this.state = {user: null};
}
setUser = () => {
const {uid} = firebase.auth().currentUser;
firebase.database().ref('Users').child(uid).on('value', r => {
const user = r.val();
this.setState({user: user});
console.log(this.state.user);
setUser(this.state.user);
});
};
componentWillMount() {
if (firebase.auth().currentUser) {
this.setUser();
}
firebase.auth().onAuthStateChanged(async () => {
console.log('authChanged');
if (!firebase.auth().currentUser) {
return null;
}
this.setUser();
});
}
render() {
return (
<div className="App">
<Nav/>
</div>
);
}
}
setUser have to be dispatched and not simply called:
store.dispatch(setUser(user));
But that's not really the react way, you'd better use mapDispatchToProps in your connect function to dispatch actions directly from component props. Something along the lines of:
import { setUser } from 'store/user';
// ...
class UserComponent extends React.Component {
// ...
someMethod() {
this.props.setUser(user);
}
}
export default connect(
null,
({setUser: setUser})
)(UserComponent);
This allows your React component to be linked to your Redux store in an optimized and bug-free way. That's also the way most developer use, so you're likely to find a lot of docs on this.
Example: Your connected Component where you want to use your setUser action with redux
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setUser} from '../../actions';
class YourComponent extends Component {
render(){
// now your redux action is passed to component as prop
// and you can use it like
this.props.setUser(some-user);
return()
}
}
export default connect(null, {setUser})(YourComponent);
first of all you have to dispatch action to change the state , second you have to connect your component to the store
to connect your component to the store
...
import { connect } from 'react-redux';
class MyComponent extends React.Component {
...
}
export default connect((store) => ({...}))
when you connect your component to the store you will have access to dispatch function in the props
to dispatch action do this :
this.props.dispatch(setUser());
I believe it's called storage
BTW it called store
I just switched out this.setState to use mobx observable, because I have multiple GET requests that fetch data. This prevents the PieChart from being re-rendered every time this.setState is called.
However, now the child component does not ever get re-rendered and stays with the initial placeholder mobxState. How can I get the PieChart child component to re-render when the data for it comes in from the API.
class Device extends React.Component {
mobxState = {
customOptions: [],
rowData: []
};
//mount data
componentDidMount() {
//call the data loader
this.fetchData();
}
fetchData = () => {
axios
.get("/custom_options.json")
.then(response => {
this.mobxState.customOptions = response.data.custom_options;
})
.then(
//data for PieChart, need this portion to render the PieChart
axios.get("/devices.json").then(response => {
this.mobxState.rowData = response;
})
);
};
render() {
return <PieChart data={this.mobxState.rowData} />;
}
}
decorate(Device, {
mobxState: observable
});
export default Device;
You need to make sure your Device component is an observer, and if you are using a MobX version below 5 you have to slice() or peek() the array in the render method.
import { observer } from "mobx-react";
class Device extends React.Component {
// ...
render() {
return <PieChart data={this.mobxState.rowData.slice()} />;
}
}
decorate(Device, {
mobxState: observable
});
export default observer(Device);
I am having bit of a wrinkle with Redux-Saga as the reducers I had done isn't updating the store as it should suppose to do.
I have used Saga to load a static in-app data and then fired the action with the payload passing the data to reducers, I did console.log() to make sure the reducers are getting the payload from action, which they are - but the problem appears to happen when I return the data into the state so that it could be accessible within the components. In props I only get default state from the reducers, any help on this matter would be highly appreciated. Following is the code I am using;
actions.js
export function loadAppAction() {
return {
type: types.LOAD_APP
}
}
export function loadAppDataAction(data) {
return {
type: types.LOAD_APP_DATA,
payload: data
}
}
api.js
import appData from '../components/appData';
export function appDataResponse() {
return appData;
}
app.js
export class App extends Component {
constructor(props) {
super(props);
const { loadAppAction } = this.props;
loadAppAction();
}
render() {
const {
initialLoadData,
activateModalAction,
deactivateModalAction,
toggleModal
} = this.props;
console.log('props', this.props)
return (
<div className="app">
{
toggleModal &&
<SignInModal
deactivateModalAction={deactivateModalAction}
/>
}
</div>
}
}
function mapStateToProps({ initialLoadReducer, toggleModalReducer }) {
console.log('lets see', initialLoadReducer);
return {
initialLoadData: initialLoadReducer,
toggleModal: toggleModalReducer
};
};
export default connect(
mapStateToProps, {
loadAppAction: actions.loadAppAction,
activateModalAction: actions.activateModalAction,
deactivateModalAction: actions.deactivateModalAction,
})
(App);
initialLoadReducers.js
export default function (state = [], action) {
switch (action.type) {
case types.LOAD_APP_DATA:
return [...action.payload];
default:
return state;
}
}
saga - index.js
function* watchLoadAppAction() {
yield takeEvery(types.LOAD_APP, loadAppSaga);
}
export default function* rootSaga() {
yield all ([watchLoadAppAction()]);
}
loadAppSaga.js
export default function* loadAppSaga(action) {
const response = yield call(api.appDataResponse);
yield put(actions.loadAppDataAction(response));
}
Following is the screenshot of my console for reference
I would suggest to call loadAppAction when componentDidMount not in the constructor. React doc also suggested the same.
https://reactjs.org/docs/react-component.html#componentdidmount
export class App extends Component {
componentDidMount() {
this.props.loadAppAction();
}
...
}
Right so, I got down to the problem here, I was trying to initialise the app with an empty array which will not going to work anyway, as the component is expecting to receive props from redux which is an empty array. Which is why, React didn't create the DOM at its first run and that caused the app to stop re-rendering even though the props are changing.
To make it work, I now initialise the app with the same data structure but with empty string values and in the next step making the data available through Redux Saga into the reducer and passing it back into the React component.
I am trying to wrap my head around ReactJS and I am stumped with an issue where I want to be able to update the value of a local variable and return the updated value.
I've read about state and I've used that when working with React Components, however, this class is just defined as const and it doesn't extend React.Component.
Is there a different way I should be defining setting the variable?
Here is a simplified version of my code:
import React from 'react';
const WelcomeForm = ({welcome}) => {
var welcomeMsg = 'Test';
DynamicContentApi.loadDynamicContent('welcome_test').then((response) => {
// response.text has content
welcomeMsg = response.text;
}).catch(() => {
welcomeMsg = '';
});
return (
<p>{welcomeMsg}</p> // Returns 'Test'
);
};
export default WelcomeForm;
The easiest option here is to change your stateless component to a stateful component.
Stateless components are just JavaScript functions. They take in an
optional input, called prop.
Stateful components offer more features, and with more features comes more baggage. The primary reason to choose class components (stateful) over functional components (stateless) is that they can have state, that is what you want to update to re-render.
Here is what you can do:
class WelcomeForm extends React.Component {
state = {
welcomeMsg: ''
}
fetchFromApi() {
DynamicContentApi.loadDynamicContent("welcome_test")
.then(response => {
this.setState({welcomeMsg: response.text});
})
.catch((e) => console.log(e));
}
componentDidMount() {
fetchFromApi();
}
render() {
return (
<p>{welcomeMsg}</p>
);
}
};
If you want, for any reason, to keep your component stateless, you will have to put the loadDynamicContent() function on the Parent and pass the text to WelcomeForm as a prop. For example:
// Your WelcomeForm Component
const WelcomeForm = ({welcomeMsg}) => (
<p>{welcomeMsg}</p>
);
// Whatever it's Parent Component is
class Parent extends React.Component {
state = {
welcomeMsg: ''
}
fetchFromApi() {
DynamicContentApi.loadDynamicContent("welcome_test")
.then(response => {
// response.text has content
this.setState({welcomeMsg: response.text});
})
.catch((e) => console.log(e));
}
componentDidMount() {
fetchFromApi();
}
render() {
<WelcomeForm welcomeMsg={this.state.welcomeMsg} />
}
}
As suggested in the comments, you can pass the DynamicContentApi logic to outside:
import ReactDOM from 'react-dom'
DynamicContentApi.loadDynamicContent('welcome_test').then((response) => {
ReactDOM.render(<WelcomeForm data={response.text} />, document.getElementById('where you wanna render this'));
}).catch(() => {
console.log('error while fetching...');
});
And where you have your component:
import React from 'react';
export default class WelcomeForm extends React.Component {
render() {
return (
<p>{this.props.data}</p>
);
}
}