score:1
i would advice you not to save posts in two places. that somewhat defeats the purpose of using redux. you actually don't need post as a state variable in posts
class. whenever there is a new state in redux store associated class will fall into updation cycle.
also, you can have a look at redux-thunk
if you are making api calls.
import thunk from 'redux-thunk';
import rootreducer from './reducers/index';
const store = createstore(
rootreducer,
applymiddleware(thunk)
);
it will help you move api fetching logic to actions and reducers and thus rendering your views clean.
change this
export const getposts = (posts) => {
return (dispatch, getstate) => {
dispatch({type: get_posts, posts })
console.log('this works i guess', posts);
}
}
to
export const getposts = (posts) => {
return (dispatch, getstate) => {
axios.get(process.env.react_app_get_posts)
.then( (res) => {
dispatch({type: get_posts, res.data })
})
})
}
}
change this
componentwillmount(){
this.getposts();
}
to
componentwillmount(){
this.props.getposts();
}
now you wont be needing a componentdidupdate
.
also, if you are wondering how to show loading... till the api call is not completed, you can add a key isfetching to your store.
const initialstate = {
post: [],
posterror: null,
posts:[],
isfecthing: false
}
and can add an action something like changefetchstats
export const getposts = (posts) => {
return (dispatch, getstate) => {
dispatch({type: change_state, false});
axios.get(process.env.react_app_get_posts)
.then( (res) => {
dispatch({type: change_status, true);
dispatch({type: get_posts, res.data })
})
})
}
}
score:0
so i finally found a purpose for componentdidupdate
the app took a little bit long to load posts maybe half a second.
so by calling componentdidupdate
, i get the posts after its finished rendering.
componentdidupdate(){
this.props.getposts(this.state.posts);
}
along with another solution by @stevek
change this
case get_posts:
return({
...state,
posts: state.posts
})
to this
import { get_posts} from '../actions/';
const initialstate = {
post: [],
posterror: null,
posts:[]
}
export default (state = initialstate, action) => {
switch (action.type) {
// doesn't get posts
case get_posts:
return{...state, posts: action.posts}
default:
return state
}
}
and i can see it after its rendered
score:0
sometimes, it may take time over a network to get a post response. in such case, if ur component gets mounted, it will make a call to the action, but because it takes time, you will get response empty/ undifined posts array. to prevent this from happening, you can go with following :
componentdidmount(){
this.props.getposts(this.state.posts);
if(!this.props.posts){
console.log(this.props.posts);
}
}
a little tweek in the render method may help too:
render() {
const {loading, posts} = this.props;
if (!this.props.isauthenticated) {
return (<redirect to='/signin' />);
}
if(loading){
return "loading..."
}
return (
{ posts &&(
<div classname="app" style={styles.wrapper}>
<h1> posts </h1>
<postlist deletepost={this.ondelete} posts={posts}/>
</div>
);)}
}
Source: stackoverflow.com
Related Query
- React is not passing state to mapStateToProps
- React / Redux: mapStateToProps not actually mapping state to props
- React Router <Link> and <Route> not passing state to Component
- REACT + REDUX: on redux state change mapStateToProps updating state but view is not rendering as per new state
- React not passing state to child via props
- React Context Provider not passing down state into children
- Passing the value of a clicked element in a child component into a button in a parent component in react via state lifting not working
- React state hook not passing changes to element
- Passing a function as a callback to a React state created with hooks did not reflect new value of variable
- React Hooks: Passing state prop is NOT a function?
- React & Redux: State of component is not updating even with mapStateToProps
- Even after redux state update mapStateToProps not returning updated props to components in react
- React component not updating with current state but mapStateToProps is updating
- Why does calling react setState method not mutate the state immediately?
- State not updating when using React state hook within setInterval
- React setState not updating state
- React Child Component Not Updating After Parent State Change
- React component not re-rendering on state change
- React - State not updated
- React - useState - why setTimeout function does not have latest state value?
- React Hooks - useEffect fires even though the state did not change
- React component not updating when store state has changed
- React shouldComponentUpdate() is called even when props or state for that component did not change
- UI not re-rendering on state update using React Hooks and form submission
- Can not update state inside setInterval in react hook
- Why is my react component not updating with state updates?
- Do not mutate state directly, Use setState() react/no-direct-mutation-state in React JS
- Can not pass state with react router dom v6 beta, state is null
- React Router v4 Redirect Passing State from Search to Results
- React Hooks - Modified state not reflecting immediately
More Query from same tag
- Calling a component by name in React Router
- Chaining redux action creator Promise.then() in react component
- Django React with i18n
- React startup ES2016
- React dynamic routes and refresh
- Add and remove data to table - React
- Can't use createRef in latest version of create-react-app
- Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in React js
- Populating Redux-Form with initial values from Redux store
- Homepage name appears behind the AppBar, How do I fix this?
- React - Return function value to setState
- why it's saying Nested block is redundant no-lone-block?
- How to validate an array with react hook form?
- How can I submit the values to backend from frontend(react) selected by the user through radio buttons?
- Using React I am trying to produce three buttons that represent the three collections, and when clicked will take you to that collection of cards
- How to add onMouseDown listener via HOC
- Can i search about some files stored in google bucket inside my react app?
- React + MobX, user Authantication, render error
- Understanding how spread works for reducer action
- How to always show a label in ChartJS in React
- How can I render Reference fields from Contentful in React?
- Image doesn't display with MUI React
- React-datepicker selected date format
- Why do I need to define the event handler `handleStatusChange` in `useEffect`?
- Calling a function inside another function in React
- React-native: How to set image in background of Layout(View)
- onClick open module
- Why do state changes before mount cause function execution but don't show on screen?
- trouble using set state correctly to update an event in react Big Calender
- Cannot get redux state inside the provider file