Home > database >  Swapi API filtering characters by gender
Swapi API filtering characters by gender

Time:10-22

I need small help. I am new to JS and i need help with the swapi api. what i have is:

fetch('https://swapi.dev/api/people/').then((response) => response.json()).then((response) =>{
  console.log(response)
})

now I need from this to filter it and get all the male characters in array same with the female.

My question is how to do that with filter and map?

CodePudding user response:

A sample e.g. of filter,

  • we set data to state after response from API.
  • we have another state to capture selected gender, and we use derived state to filter which on each render calculates (can optimize using useMemo but for test data as so its premature to do so, tbh).

const { useState, useEffect } = React;

const App = () => {
  const [data, setData] = useState([]);
  const [gender, setGender] = useState();

  useEffect(() => {
    fetch("https://swapi.dev/api/people/")
      .then((response) => response.json())
      .then((response) => {
        setData(response.results);
      });
  }, []);

  const filtered = gender ? data.filter((d) => d.gender === gender) : data;

  return (
    <div>
      <select onChange={(e) => setGender(e.target.value)}>
        <option value="">All</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>
      <hr></hr>
      { (data && data.length) > 0 ? filtered.map((d) => (
        <p key={d.name}>
          {d.name} - {d.gender}
        </p>
      )) : "loading...."}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related