I have an array "movies" of objects like this:
{
id: "some id",
title: "some title",
actors: []
}
As you can see, the actors array stays empty, because I don't add actors while I am adding a movie. I want to add actors later on, while being on http://localhost:3000/movies/<movieId> .
I do this by this Form. Im just selecting a actor, from already existing lists of actors.
const PostForm = ({ addActorToMovie, movie, actors, history }, props) => {
const handleSubmit = (values) => {
addActorToMovie(values);
// history.push(`/movies/${movie.id}`);
};
let actorsList =
actors.length > 0 &&
actors.map((item, i) => {
return (
<option value={`${item.firstName}, ${item.lastName}`}>
{item.firstName + item.lastName}{" "}
</option>
);
});
return (
<div>
<h3>Add Actor</h3>
<Formik
initialValues={{
actor: "",
}}
onSubmit={(values) => handleSubmit(values)}
enableReinitialize={true}
>
<Form>
<Field name="actor" component="select">
<option value="null"> </option>
{actorsList}
</Field>
<button type="submit">Zatwierdz</button>
</Form>
</Formik>
</div>
);
};
const mapStateToProps = (state, props) => {
return {
movie: state.movie,
actors: state.actors,
};
};
const mapDispatchToProps = {
addActorToMovie,
};
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(PostForm)
);
The form works. Although instead of adding value to my actors array. It creates a new object under movies array which looks like this:
actors: {actor: 'Some actor name'}
My reducers looks like this. Probably this is the source of the problem, but I don't really know how to do this.
export const movieReducer = (state = [], action) => {
switch (action.type) {
case "MOVIE_ADD":
return [...state, action.payload];
case "MOVIE_DELETE":
return [...state.filter((el) => el.id !== action.payload.id)];
case "MOVIEACTOR_ADD":
return {
...state,
actors: action.payload
};
default:
return state;
}
};
What I want to do is of course push the actor which i enter in my Formik to an array of specified movie.
ADD_ACTOR_TO_MOVIEshould include which movie it's adding an actor to. We should also see the UI component that is dispatching the action as well.