I am learning react hence this could be primitive problem but after lot of effort and searching I could not get this to work. Any help really appreciated.
Requirement
I have a html form which is filed by API response after user clicking a button. After API response user should be able to change the filled data.
Problem From redux i set the properties from api call. This information set to state which uses to render to input field. when user types the data in input filed i cannot seems to change the state without causing infinite loop or not updating state at all.
This is my current work
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
title: 'Initial title'
}
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.hasOwnProperty('todoInfo')) {
const {title} = this.props.todoInfo;
if (title !== prevState.title) {
this.setState({
title: title
});
}
}
}
handleChange = (event) => {
const {name, value} = event.target;
this.setState((prevState) => ({
...prevState,
title: value
}));
}
render() {
const {title} = this.state;
return (
<div>
<p>
<button onClick={() => this.props.fetchData()}> fetch data</button>
</p>
<p>
<input type="text" id="fname" name="fname" value={this.state.title}
onChange={this.handleChange}></input>
</p>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log('map state to props ' + JSON.stringify(state));
return {
todoInfo: state.todoReducers.todoInfo
};
};
const mapDispatchToProps = (dispatch) => ({
fetchData: () =>
dispatch(fetchData())
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
actions
export const fetchData = () => {
return (dispatch) => {
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
const todoInfo = response.data;
dispatch({
type: GET_TODO,
payload: todoInfo
})
})
.catch(error => {
const errorMsg = error.message;
console.log(errorMsg);
});
};
};
reducer
const todoReducers = (state = {}, action) =>{
switch (action.type) {
case GET_TODO:
console.log('here ' + JSON.stringify(action));
return {
...state,
todoInfo: action.payload
};
default:
return state;
}
}
export default todoReducers;
I want my input text field load data from API then update with any user input. If they click fetch data again then user inputs are replaced by API fetch data. how to do this ?
EDIT Solution according to accepted answer can be found https://github.com/mayuraviraj/react-redux-my-test