Before adding redux, a simple solution with an internal state looks like this:
import React, {useState} from 'react'
const Sample = () => {
const [inputValue, setInputValue] = useState("");
const handleChange = (e) => {
setInputValue(e.target.value)
}
return(
<input type='text' value={inputValue} onChange={handleChange} />
)
}
Now, try it with redux implementation:
import React from 'react';
import {useDispatch, useSelector} from 'react-redux';
const Sample = () => {
const dispatch = useDispatch();
const inputValue = useSelector(state => state.sample.value)
const handleChange = (e) => {
dispatch({type: 'CHANGE_INPUT_VALUE`, payload: e.target.value})
}
return(
<input type='text' value={inputValue} onChange={handleChange}>
)
}
the reducer might look like this:
const initialState = {
value: "";
}
const sampleReducer = (state=initialState, action) => {
switch(action.type){
case 'CHANGE_INPUT_VALUE':
return{
...state,
value: action.payload
}
// other cases ...
default:
return state
}
}
I rather to define actions and selector in separated files and import them where they need:
Sample action file:
export const CHAGNE_INPUT_VALUE = 'CHANGE_INPUT_VALUE';
export const changeInputValue = (value) => ({type: CHAGNE_INPUT_VALUE, payload: value})
Sample selector file:
export const selectInputValue = (state) => state.sample.value
Now apply them to the Sample component:
import React from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {changeInputValue} from 'path/to/action/file';
import {selectInputValue} from 'path/to/selector/file';
const Sample = () => {
const dispatch = useDispatch();
const inputValue = useSelector(selectInputValue)
const handleChange = (e) => {
dispatch(changeInputValue(e.target.value))
}
return(
<input type='text' value={inputValue} onChange={handleChange}>
)
}
Now, back to the question:
Yes, you could add anything as a payload to the reducer, for example:
dispatch(updateUserProfile({name: "", age: 0, image: "", children: [], ...}))
case UPDATE_PROFILE:
return {
...state,
name: action.payload.name,
age: action.payload.age,
}