Home > Net >  Buttons displaying both times
Buttons displaying both times

Time:08-25

The issue is lying in my Sean Connery and Roger Moore list of movies buttons. When I click on Sean Connery List of Movies, it displays Connery movies on Roger Moore's list too, and vice versa.

Prettier 2.7.1 Playground link

--parser babel

Input:

import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";

const Button = styled.button`
  background-color: black;
  color: white;
  font-size: 20px;
  padding: 10px 60px;
  border-radius: 5px;
  margin: 10px 0px;
  cursor: pointer;
`;

function ButtonClick() {
  const [users, setUsers] = useState();
  const fetchData = (type) => {
    axios
      .get(
        "https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
      )
      .then((response) => {
        console.log(response.data)
        const mappedArray = response.data
          .map(
            (item) =>
              item[type] ||
              (type === "directors" && item.director) ||
              (type === "title_song" && item.title_song) ||
              (type === "movie_year" && item.movie_year)
          )
          .filter((uniqueVal) => uniqueVal);
        setUsers({ [type]: Array.from([...new Set(mappedArray)]) });
        // console.log(movies)
      });
  };
  const [movies, setMovies] = useState();
  const fetchMovieData = (name) => {
      axios
      .get(
        "https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
      ).then(response => {
        console.log(response.data)
        setMovies(response.data.filter(item => item.bond_actor === name).map(item => item.movie_title));
        console.log("Hello World")
        console.log("Hello World")
        // console.log()
      })
    };

  return (
    <div>
      <div>
        <h2>Bond Database</h2>
        <h5>
          Click on the buttons to see the list of all the bond movie's
          directors, bond actors, release year, and title songs
        </h5>

        <Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
        {users && (
          <ul>
            {users?.bond_actor?.map((user, index) => (
              <li key={index}>
                <a href="https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies">
                  {user}
                </a>
              </li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchData("directors")}>Directors</Button>
        {users && (
          <ul>
            {users?.directors?.map((director) => (
              <li key={director}>{director}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchData("title_song")}>Songs</Button>
        {users && (
          <ul>
            {users?.title_song?.map((title_song) => (
              <li key={title_song}>{title_song}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
        {users && (
          <ul>
            {users?.movie_year?.map((movie_year) => (
              <li key={movie_year}>{movie_year}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchMovieData("Sean Connery")}>Sean Connery's List of Movies</Button>
        {movies && (
          // console.log(movies),
          <ul>
            {movies?.map((movie) => (
            // console.log(movie),
              <li key={movie}>{movie}</li>
            ))}
          </ul>
          
        )
        }
        
      </div>
      <div>
        <Button onClick={() => fetchMovieData("Roger Moore")}>Roger Moore List of Movies</Button>
        {movies && (
          <ul>
            {movies?.map((movie) => (
              // console.log(moviesR),
              <li key={movie}>{movie}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}

export default ButtonClick;

I'd assume the issue is that both buttons are using the same state, but since the names have spaces, I don't know how to create different states for the two buttons. If I get some assistance on this, it would be much appreciated.

CodePudding user response:

You can follow this:

import React, { useState } from "react";
import styled from "styled-components";
import axios from "axios";

const Button = styled.button`
  background-color: black;
  color: white;
  font-size: 20px;
  padding: 10px 60px;
  border-radius: 5px;
  margin: 10px 0px;
  cursor: pointer;
`;

function ButtonClick() {
  const [users, setUsers] = useState();
  const fetchData = (type) => {
    axios
      .get(
        "https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
      )
      .then((response) => {
        console.log(response.data);
        const mappedArray = response.data
          .map(
            (item) =>
              item[type] ||
              (type === "directors" && item.director) ||
              (type === "title_song" && item.title_song) ||
              (type === "movie_year" && item.movie_year)
          )
          .filter((uniqueVal) => uniqueVal);
        setUsers({ [type]: Array.from([...new Set(mappedArray)]) });
        // console.log(movies)
      });
  };
  const [movies, setMovies] = useState({});
  const fetchMovieData = (name) => {
    axios
      .get(
        "https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies"
      )
      .then((response) => {
        console.log(response.data);
        setMovies({
          [name]: response.data
            .filter((item) => item.bond_actor === name)
            .map((item) => item.movie_title)
        });
        console.log("Hello World");
        console.log("Hello World");
        // console.log()
      });
  };

  return (
    <div>
      <div>
        <h2>Bond Database</h2>
        <h5>
          Click on the buttons to see the list of all the bond movie's
          directors, bond actors, release year, and title songs
        </h5>

        <Button onClick={() => fetchData("bond_actor")}>Bond Actors</Button>
        {users && (
          <ul>
            {users?.bond_actor?.map((user, index) => (
              <li key={index}>
                <a href="https://iznfqs92n3.execute-api.us-west-1.amazonaws.com/dev/api/v2/movies">
                  {user}
                </a>
              </li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchData("directors")}>Directors</Button>
        {users && (
          <ul>
            {users?.directors?.map((director) => (
              <li key={director}>{director}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchData("title_song")}>Songs</Button>
        {users && (
          <ul>
            {users?.title_song?.map((title_song) => (
              <li key={title_song}>{title_song}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchData("movie_year")}>Movie Year</Button>
        {users && (
          <ul>
            {users?.movie_year?.map((movie_year) => (
              <li key={movie_year}>{movie_year}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchMovieData("Sean Connery")}>
          Sean Connery's List of Movies
        </Button>
        {movies && (
          // console.log(movies),
          <ul>
            {movies?.["Sean Connery"]?.map((movie) => (
              // console.log(movie),
              <li key={movie}>{movie}</li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <Button onClick={() => fetchMovieData("Roger Moore")}>
          Roger Moore List of Movies
        </Button>
        {movies && (
          <ul>
            {movies?.["Roger Moore"]?.map((movie) => (
              // console.log(moviesR),
              <li key={movie}>{movie}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}

export default ButtonClick;

CodePudding user response:

One way of handling this is to take a reducer approach:

  const [movies, setMovies] = useState({});
  const fetchMovieData = (name) => {
      axios
      .get(
        "..."
      ).then(response => {
        ...
        const newMoviesState = {...movies};
        newMoviesState[name] = response.data.filter(item => item.bond_actor === name).map(item => item.movie_title)
        setMovies(newMoviesState);
        ...
      })
    };

Then, in your JSX for the buttons:

      <div>
        <Button onClick={() => fetchMovieData("Sean Connery")}>Sean Connery's List of Movies</Button>
        {movies["Sean Connery"] && (
          ...
          <ul>
            {movies["Sean Connery"]?.map((movie) => (
            // console.log(movie),
              <li key={movie}>{movie}</li>
            ))}
          </ul>
          
        )
        }
        
      </div>
  • Related