I'm using react-redux to create a simple CRUD app. The ability to import titles and descriptions from the input, store them in the array, and delete them has been implemented, but the ability to modify them is difficult and asks for help.
action.js
export const addPosting = (title, description) => {
return {
type: ADD_POSTING,
post: {
id: nextId++,
title,
description
}
};
}
export const updatePosting = (payload) => {
return {
type: UPDATE_POSTING,
payload
}
}
export const deletePosting = (id) => {
return {
type: DELETE_POSTING,
id
}
}
postReducer.js
const initialState = [{
id: 1,
title: ' This is First Post',
description: 'Lorem ipsum dolor sit amet consectetur, adipisicing elit.',
}]
const posts = (state = initialState, action) => {
switch (action.type) {
case ADD_POSTING:
return state.concat(action.post);
case DELETE_POSTING:
return state.filter(post => post.id !== action.id);
case UPDATE_POSTING:
return // help
default:
return state;
}
};
The method that I tried was not modified.
case UPDATE_POSTING:
return state.map(post => post.id === action.id ? {
...action.post,
} :
post
)
form.jsx
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { updatePosting } from '../store/actions';
const Modal = ({ post, modal, close }) => {
// update redux
const posts = useSelector(state => state.posts);
const dispatch = useDispatch();
const onUpdate = (title, description) =>
dispatch(updatePosting(title, description));
// inputs
const [inputs, setInputs] = useState({
title: post.title,
description: post.description,
});
const { title, description } = inputs;
const onChange = e => {
const { value, name } = e.target;
setInputs({
...inputs,
[name]: value,
});
};
const onSubmit = e => {
e.preventDefault();
onUpdate(title, description);
setInputs({
title: post.title,
description: post.description,
});
};
return (
<React.Fragment>
{modal ? (
<React.Fragment>
<div className="modal-container">
<form className="modal" onSubmit={onSubmit}>
<div className="title">
<input
className="titleInput"
type="text"
name="title"
required
value={title}
onChange={onChange}
/>
<button onClick={close}>x</button>
</div>
<div className="des">
<textarea
name="description"
className="modal-des"
cols="30"
rows="10"
required
value={description}
onChange={onChange}
></textarea>
</div>
<button onSubmit={onSubmit}>submit</button>
</form>
</div>
</React.Fragment>
) : null}
</React.Fragment>
);
};
export default Modal;
Thank you for your help in solving this problem.

