Reducer isn't updating state - javascript

I can't get reducer to return updated state. It returns the updated state with correct info on 2nd time button click. workflow is the state which has tasks: [], taskId: '' and hasError variable. On button click I call onUnassign dispatch action which returns an error to invoke WORKFLOW_VALIDATION_DATA_ERROR reducer action which updates state variable hasError to true but hasError displays true on 2nd button click. I'm not able to figure it out why? Below is my code:
const DisActionConnected: React.FC = () => {
const dispatch = useDispatch();
const {tasks, workflow} = useSelector((state: IRootState) => state.workflow);
const onUnassign = () => {
if (tasks && tasks.length > 0) {
dispatch(setUnassign(name));
console.log(workflow) // here hasError is true on 2nd time not first time
}
};
return (
<div>
<DisActions
userId={userId}
onUnassign={onUnassign}
/>
</div>
);
};
store action
export const setUnassign = (name: string) => {
return {
type: TASK_UNASSIGN_PENDING,
payload: {
name
}
}
};
reducer function
export function workflowReducer(
state: IWorkflowState = initialState,
action: WorkflowActionsType
): IWorkflowState {
switch(action.type) {
case WORKFLOW_VALIDATION_DATA_ERROR:
return {...state, hasError: true};
case TASK_UNASSIGN_PENDING:
return {...state};
default:
return {...state};
};
}
STATE
export interface IWorkflowState {
tasks: ITask[];
taskId: string;
hasError: boolean | null
};
const initialState: IWorkflowState = {
tasks: [],
taskId: '',
hasError: false
};
export function* setUnassignDis() {
const errorMessage = "error saving data"
yield put({
type: WORKFLOW_VALIDATION_DATA_ERROR,
payload: {errorMessage}
});
}
function* workflowSaga() {
yield takeEvery(WorkflowStore.TASK_UNASSIGN_PENDING, setUnassignDis);
}

React state updates are not instantaneous and this is how Javascript closures work. workflow can never be anything but what the workflow state value is when onUnassign is called. The current workflow value is closed over in callback scope. When the button is clicked again and the onUnassign callback is called it closes over the updated state from the previous update.
If you want to log updated state values then use the useEffect hook with appropriate dependency.
Example:
const {
tasks,
workflow
} = useSelector((state: IRootState) => state.workflow);
// Log when workflow state updates
React.useEffect(() => {
console.log(workflow);
}, [workflow]);
const onUnassign = () => {
if (tasks?.length) {
dispatch(setUnassign(name));
}
};
...

Related

How to update redux state using onChange with React Redux

I'm using React Redux and want to be able to change the title and description of a post, using the onChange method. When only using React the way you would do this is that you keep an useState which you change whenever a change occurs, but I can't seem to get it to work with using redux in react. Instead of the state changing the original title, and description remains and cannot be changed.
From what I have read the basic idea is to have a listener on the input (onChange, usually) and have that fire a redux action. You then have the action tell the reducer to make the change to the store.
I have tried doing this, but could make it work correctly. What am I doing wrong and how do you solve it? I'm also wondering how do I specify that I want to change either title or description when using onChange, or do I simply send everything in post each time a change occurs?
This is what the redux state looks like when entering a post:
{
auth: {
isSignedIn: true,
user: {
id: '624481f22566374c138cf974',
username: 'obiwan',}
},
posts: {
'62448632b87b223847eaafde': {
_id: '62448632b87b223847eaafde',
title: 'hellothere',
desc: 'its been a long time since I heard that name...',
username: 'vorbrodt',
email: 'example#gmail.com',
categories: [],
createdAt: '2022-03-30T16:32:50.158Z',
updatedAt: '2022-03-30T16:32:50.158Z',
__v: 0
}
},
}
Here is where the onChange happens.
Post.js
import { getPostById, editPost } from "../actions";
const Post = ({ getPostById, editPost, username }) => {
const [updateMode, setUpdateMode] = useState(false);
let { id } = useParams();
let post = useSelector((state) => state.posts[id]);
const handleInputChange = (e) => {
try {
editPost(e.target.value);
} catch (err) {}
};
return (
<div className="post">
<div className="post-wrapper">
{updateMode ? (
<input
type="text"
value={post.title}
className="post-title-input"
autoFocus
onChange={(e) => handleInputChange(e)}
/>
) : (
<h1 className="post-title">
{post.title}
</h1>
)}
<div className="desc-area">
{updateMode ? (
<textarea
className="post-desc-input"
value={post.desc}
onChange={(e) => handleInputChange(e)}
/>
) : (
<p className="post-desc">{post.desc}</p>
)}
</div>
</div>
</div>
);
};
const mapStateToProps = (state) => {
return { username: state.auth.user.username };
};
export default connect(mapStateToProps, { getPostById, editPost })(Post);
Here is the action creator:
//edit post in redux state
const editPost = (postValues) => (dispatch) => {
dispatch({ type: EDIT_POST, payload: postValues });
};
And here is the reducer which is suppose to change the state.
postReducer.js
import _ from "lodash";
import { GET_POSTS, GET_POST, CREATE_POST, EDIT_POST } from "../actions/types";
function postReducer(state = {}, action) {
switch (action.type) {
case GET_POSTS:
return { ...state, ..._.mapKeys(action.payload, "_id") };
case GET_POST:
return { ...state, [action.payload._id]: action.payload };
case CREATE_POST:
return { ...state, [action.payload._id]: action.payload };
case EDIT_POST:
//here the change should occur, not sure how to specify if title or desc should
//change
return { ...state, [action.payload._id]: action.payload };
default:
return state;
}
}
export default postReducer;
Hey there something like this should be of help
const handleInputChange = (e, key, id) => {
try {
editPost({ [key]: e.target.value, id });
} catch (err) {}
};
Usage
<textarea
className="post-desc-input"
value={post.desc}
onChange={(e) => handleInputChange(e, "title", post.id)}
/>
action
const editPost = (postValues) => (dispatch) => {
dispatch({ type: EDIT_POST, payload: postValues });
};
Reducer
case EDIT_POST:
//here we destructure the id and return the data without the id cause we //need it below
const {id, ...newData} = action.payload
const indexToUpdate = state.posts.find(post => post.id === id)
const newPostsData = [...state.posts]
//Here we update the actual object and its property that is in the state at //the specific value
newPostsData[indexToUpdate] = {...newPostData[indexToUpdate], {...newData}
return { ...state, posts: newPostsData};

Updating UI after state update in Redux

EDIT:
I fixed the problem in the reducer...changed this:
case ADD_LIST_ITEM:
return {
...state,
lists: {
...state.lists.map(list =>
list._id === payload.id
? { ...list, listItems: payload.data }
: list
)
},
loading: false
};
to this:
case ADD_LIST_ITEM:
return {
...state,
lists: [
...state.lists.map(list =>
list._id === payload.id
? { ...list, listItems: payload.data }
: list
)
],
loading: false
};
Stupid error on my part.
I have a MERN todo application using redux for state management and useEffect() for UI updates (all functional instead of class-based components). However, when I change state in the redux store, the UI does not update. This seems to only happen during an update triggered by a post request from the front end to the backend, where I pass data to an action, which is handled in a reducer (a js file rather than the useReducer() hook in this app). My backend will update properly, but the UI will crash.
What happens is, I input, say, a new list item in a given todo list, and the error I get is:
Uncaught TypeError: list.lists.map is not a function
at Dashboard (Dashboard.jsx:32)
I'm not sure where to use an additional useEffect(), if needed, or if there's a problem in my reducer...here's the relevant flow (removed all className declarations and irrelevant parts):
/* Dashboard.jsx */
// imports //
const Dashboard = ({ auth: { user }, list, getLists }) => {
useEffect(() => {
getLists();
}, [getLists]);
return (
<>
<p>Lists...</p>
{list.lists &&
list.lists.map(list => <List key={list._id} list={list} />)}
</>
);
};
Dashboard.propTypes = {
getLists: PropTypes.func.isRequired,
list: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
list: state.list
});
export default connect(mapStateToProps, { getLists })(Dashboard);
/* List.jsx */
// imports
const List = ({ list, addListItem, getLists }) => {
const [text, setText] = useState('');
useEffect(() => {
getLists();
}, []);
const handleAddItem = e => {
e.preventDefault();
addListItem(list._id, { text });
setText('');
};
return (
<div>
{list.listItems &&
list.listItems.map((item, index) => (
<ListItem
key={index}
item={item}
listId={list._id}
itemIndex={index}
/>
))}
<div>
<form onSubmit={handleAddItem}>
<input
type="text"
name="text"
placeholder="add a to-do item"
value={text}
onChange={e => setText(e.target.value)}
/>
<input type="submit" value="add" />
</form>
</div>
</div>
);
};
List.propTypes = {
addListItem: PropTypes.func.isRequired,
getLists: PropTypes.func.isRequired
};
export default connect(null, {
addListItem,
getLists
})(List);
/* list.actions.js */
// imports
export const addListItem = (listId, text) => async dispatch => {
try {
const res = await api.post(`/lists/${listId}`, text); // returns all list items after adding new item
dispatch({
type: ADD_LIST_ITEM,
payload: { id: listId, data: res.data }
});
} catch (err) {
dispatch({
type: LIST_ERROR,
payload: { message: err.response.statusText, status: err.response.status }
});
}
};
/* list.reducer.js */
// imports
const initialState = {
lists: [],
list: null,
loading: true,
error: {}
};
const list = (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case GET_LISTS:
return { ...state, lists: payload, loading: false };
case LIST_ERROR:
return { ...state, error: payload, loading: false };
case ADD_LIST_ITEM:
return {
...state,
lists: {
...state.lists.map(list =>
list._id === payload.id
? { ...list, listItems: payload.data }
: list
)
},
loading: false
};
default:
return state;
}
};
export default list;
I assume when creating your app's store, you are passing list as rootReducer,
Meaning your app's main state is exactly the state list is managing.
So if you need to access property lists of the state, you need to do it like this:
const mapStateToProps = state => ({
lists: state.lists /// state in here is exactly the state of list reducer
});
Now, in Dashboard lists is that array that you manipulate in list reducer.
Also, you have defined a property also named list in list reducer. It is initially defined to be null, also in the reducer, you never change it:
const initialState = {
lists: [],
list: null, /// none of actions ever change this, meaning it's currently useless.
loading: true,
error: {}
};

Two click for dispatch action Redux

I use REDUX in my REACTJS application. I want to retrieve the button ID after clicking the button and send it to my store. It's only works after the second click. Can you help me ? My code:
My function :
gotoidee (e) {
let test= this.state.data[e.target.id];
console.log("test" +test.titre);
const action = { type: "SAVE_IDEE_ID", value:this.state.data[e.target.id]};
this.props.dispatch(action);
console.log(this.props.ideeId.titre);
}
const mapStateToProps = (state) => {
return {
ideeId: state.saveIdee.ideeId
}
}
export default connect(mapStateToProps)(liste_idee)
My reducer :
const initialState = { ideeId: [] }
function saveIdee (state = initialState, action) {
let nextState
switch (action.type) {
case 'SAVE_IDEE_ID':
nextState = {
...state,
ideeId: action.value
}
return nextState
default:
return state
}
}
export default saveIdee
My button :
<Button type="submit" id={ideeId} onClick={this.gotoidee}>Marche</Button>
gotoidee (e) {
// check here if the click is happening by putting a console here
let test= this.state.data[e.target.id];
console.log("test" +test);
const action = { type: "SAVE_IDEE_ID", value:test};
this.props.dispatch(action);
}
render(){
console.log(this.props.ideeId); // check the updated value
}

Why is onInput not a function? A question about useEffect()

I am pretty new to react and hooks, and I'm struggling with useEffect(). I've watched all the vids and read all the docs and still can't quite wrap my head around the error I'm getting. ("onInput is not a function" when my New Article route loads). onInput points to a callback function in my form-hook.js. Why isn't it registering?
In my input.js component:
import React, { useReducer, useEffect } from 'react';
import { validate } from '../../util/validators';
import './Input.css';
const inputReducer = (state, action) => {
switch (action.type) {
case 'CHANGE':
return {
...state,
value: action.val,
isValid: validate(action.val, action.validators)
};
case 'TOUCH': {
return {
...state,
isTouched: true
}
}
default:
return state;
}
};
const Input = props => {
const [inputState, dispatch] = useReducer(inputReducer, {
value: props.initialValue || '',
isTouched: false,
isValid: props.initialValid || false
});
const { id, onInput } = props;
const { value, isValid } = inputState;
useEffect(() => {
console.log(id);
onInput(id, value, isValid)
}, [id, value, isValid, onInput]);
const changeHandler = event => {
dispatch({
type: 'CHANGE',
val: event.target.value,
validators: props.validators
});
};
const touchHandler = () => {
dispatch({
type: 'TOUCH'
});
};
//if statement to handle if you are updating an article and touch the category.... but it's valid
const element =
props.element === 'input' ? (
<input
id={props.id}
type={props.type}
placeholder={props.placeholder}
onChange={changeHandler}
onBlur={touchHandler}
value={inputState.value}
/>
) : (
<textarea
id={props.id}
rows={props.rows || 3}
onChange={changeHandler}
onBlur={touchHandler}
value={inputState.value}
/>
);
return (
<div
className={`form-control ${!inputState.isValid && inputState.isTouched &&
'form-control--invalid'}`}
>
<label htmlFor={props.id}>{props.label}</label>
{element}
{!inputState.isValid && inputState.isTouched && <p>{props.errorText}</p>}
</div>
);
};
export default Input;
useEffect(() => {onInput points to the onInput prop in NewArticle.js component where users can enter a new article.
import Input from '../../shared/components/FormElements/Input';
import { useForm } from '../../shared/hooks/form-hook';
const NewArticle = () => {
const [formState, inputHandler] = useForm({
title: {
value: '',
isValid: false
}
}, false );
return (
<Input
id="title"
element="input"
type="text"
label="Title"
onInput={inputHandler}
/> );
};
export default NewArticle;
...and then in my form-hook.js inputHandler is a callback. So, onInput points to a callback function through a prop. It was working, registering onInput as a function and then, all of a sudden it was throwing an error. What gives?
import { useCallback, useReducer } from 'react';
const formReducer = (state, action) => {
switch (action.type) {
case 'INPUT_CHANGE':
let formIsValid = true;
for (const inputId in state.inputs) {
if (!state.inputs[inputId]) {
continue;
}
if (inputId === action.inputId) {
formIsValid = formIsValid && action.isValid;
} else {
formIsValid = formIsValid && state.inputs[inputId].isValid;
}
}
return {
...state,
inputs: {
...state.inputs,
[action.inputId]: { value: action.value, isValid: action.isValid }
},
isValid: formIsValid
};
case 'SET_DATA':
return {
inputs: action.inputs,
isValid: action.formIsValid
};
default:
return state;
}
};
export const useForm = (initialInputs, initialFormValidity) => {
const [formState, dispatch] = useReducer(formReducer, {
inputs: initialInputs,
isValid: initialFormValidity
});
const inputHandler = useCallback((id, value, isValid) => {
dispatch({
type: 'INPUT_CHANGE',
value: value,
isValid: isValid,
inputId: id
});
}, []);
const setFormData = useCallback((inputData, formValidity) => {
dispatch({
type: 'SET_DATA',
inputs: inputData,
formIsValid: formValidity
});
}, []);
return [formState, inputHandler, setFormData];
};
Thanks, ya'll.
I can give you some advice on how to restructure your code. This will ultimately solve your problem.
Maintain a single source of truth
The current state of your UI should be stored in a single location.
If the state is shared by multiple components, your best options are to use a reducer passed down by the Context API (redux), or pass down the container component's state as props to the Input component (your current strategy).
This means you should remove the Input component's inputReducer.
The onInput prop should update state in the container component, and then pass down a new inputValue to the Input component.
The DOM input element should call onInput directly instead of as a side effect.
Remove the useEffect call.
Separation of Concerns
Actions should be defined separately from the hook. Traditionally, actions are a function that returns an object which is passed to dispatch.
I am fairly certain that the useCallback calls here are hurting performance more than helping. For example inputHandler can be restructured like so:
const inputChange = (inputId, value, isValid) => ({
type: 'INPUT_CHANGE',
value,
isValid,
inputId
})
export const useForm = (initialInputs, initialFormValidity) => {
const [formState, dispatch] = useReducer(formReducer, {
inputs: initialInputs,
isValid: initialFormValidity,
})
const inputHandler = (id, value, isValid) => dispatch(
inputChange(id, value, isValid)
)
}
Learn how to use debugger or breakpoints in the browser. You would quickly be able to diagnose your issue if you put a breakpoint inside your useEffect call.

redux state doesnt change

I have setup the redux store but when I try to make changes to the state using mapStateToProps and mapDispatchToProps I get always the default state. So at account.js I want to get the selected language and then add it to the redux store. I try to call it in other components but I always end up with reducers/Language.js defaultState. What I'm doing wrong?
Account.js
class Account extends React.Component {
static navigationOptions = ({ navigation }) => {};
constructor(props) {
super(props);
this.state = {
language: {
sq: true,
en: false,
selected: '',
},
};
}
changeLanguage = (selected) => {
if (this.state.sq) {
this.setState({ selected: 'sq' });
} else {
this.setState({ selected: 'en' });
}
};
render() {
const navigation = this.props.navigation;
return (
<ScrollView>
<View>
<ThemeProvider>
<TableView header={I18n.t('account.lang_label')}>
<CheckboxRow
selected={this.state.language.sq}
onPress={() => {
this.setState(state => ({
language: {
sq: !state.language.sq,
en: !state.language.en,
},
}));
this.changeLanguage();
}}
title={I18n.t('account.albanian')}
/>
<CheckboxRow
selected={this.state.language.en}
onPress={() =>
this.setState(state => ({
language: {
en: !state.language.en,
sq: !state.language.sq,
},
}))
}
title={I18n.t('account.english')}
/>
</TableView>
</ThemeProvider>
</View>
</ScrollView>
);
}
}
const mapDispatchToProps = dispatch => {
return {
changeLanguage: (selected) => { dispatch(changeLanguageEn(selected))},
};
};
const mapStateToProps = state => {
return {
language: state.language.selected,
};
};
export default withNavigation(connect(
mapStateToProps,
mapDispatchToProps
)(Account));
actions/Language.js
import {CHANGE_LANGUAGE_EN, CHANGE_LANGUAGE_AL} from "./types";
export const changeLanguageEn = (language) => {
return {
type: CHANGE_LANGUAGE_EN,
lang: language,
}
};
export const changeLanguageAl = (language) => {
return {
type: CHANGE_LANGUAGE_AL,
lang: language,
}
};
reducers/Language.js
const defaultState = {
lang: '',
};
export default function reducer(state = defaultState, action) {
switch (action.type) {
case 'CHANGE_LANGUAGE_EN':
return {...state, lang: 'en'};
case 'CHANGE_LANGUAGE_AL':
return Object.assign({}, state, {
lang: 'sq',
});
default:
return state;
}
}
In your mapStateToProps function try with state.lang directly
const mapStateToProps = state => {
return {
language: state.lang,
};
};
Hope this will work.
Not entirely sure I understand your question, but it sounds like you're trying to update the redux state with the internal state of Account? You should be able to do:
this.props.changeLanguage(this.state.language.selected)
You have a method on your component defined changeLanguage as well, perhaps you could do the line above in that method, after changing the internal state
additionally, in your changeLanguage method in your Account class, I don't think this.state.sq exists since sq is a key in the language state object. Instead it should be this.state.language.sq. You don't need to add the selected argument to this method either. Try making your changeLanguage method to look like this
changeLanguage = () => {
if (this.state.sq) {
this.setState({ language.selected: 'sq' });
} else {
this.setState({ language.selected: 'en' });
}
// dispatch your action here after updating the state
this.props.changeLanguage(this.state.language.selected)
};
Now calling this.changeLanguage(); will update your internal state, and then dispatch your changeLanguage redux action
You are accessing the selected language incorrectly. state.language.selected.
In the reducer you are adding lang property in the state, so access it with the same property name in the mapStateToProps.
const mapStateToProps = state => {
return {
language: state.language.lang,
};
};

Categories