2

I am using the NHL api to try to grab players stats for a given season. I have a utility function with these season values :

export const seasonOptions = [
  { value: "19861987", label: "1986/1987" },
  { value: "19871988", label: "1987/1988" },
  { value: "19881989", label: "1988/1989" },
  { value: "19891990", label: "1989/1990" },
  { value: "19901991", label: "1990/1991" },
  { value: "19911992", label: "1991/1992" },
  { value: "19921993", label: "1992/1993" },
  { value: "19931994", label: "1993/1994" },
  { value: "19941995", label: "1994/1995" },
  { value: "19951996", label: "1995/1996" },
];

... and so on. In my component I have this state to setSelect on what was selected:

 const [select, setSelect] = useState(seasonOptions[seasonOptions.length - 1]);
 

  const handler = (selected) => {
 
      setSelect((select) => select);
      handlePlayerStats(
        `https://statsapi.web.nhl.com/api/v1/people/${props.playerId}/stats?stats=statsSingleSeason&season=${selected.value}`
      );
    }
  };


<Select
        id="select"
        instanceId={"select"}
        options={seasonOptions}
        placeholder={select.label}
        autoFocus
        value={select.value}
        onChange={handler}
      />

Which calls this custom hook:

const handlePlayerStats = async (url) => {
    try {
      const req = await fetch(url).then((response) => response.json());
      console.log(req);
      if (req.messageNumber) {
        setFetchedData([]);
      } else if (req.stats[0].splits.length > 0) {
        setFetchedData(req);
      } 
    } catch (error) {
      console.log(error);
    }
  };

I'm not really sure how to go about looping through all the seasonOptions dynamically and filtering out each season where req.stats[0].splits.length === 0?

Here is the codesandbox link for anyone curious: https://codesandbox.io/s/friendly-kapitsa-c97rzy?file=/components/PlayerStats.js:357-855

3
  • 1
    Just to make sure I got it right. You want to basically delete every object from req.stats that has the splits smaller than 0? And also splits is what, an array, or a string ? Because length smaller than 0 is illogical. Commented Oct 11, 2022 at 19:43
  • Can you try to develop a code sandbox i think i can help you with this one.! Great Job so far checkout my example of how to access the values using ````.map()``` method for the first part of your question Commented Oct 11, 2022 at 20:01
  • 1
    @AlexMatei My bad I meant to type req.stats[0].splits.length ===0. For example: statsapi.web.nhl.com/api/v1/people/8471214/… Here splits is populated but if you change the season to statsapi.web.nhl.com/api/v1/people/8471214/… Splits is now an empty array. Commented Oct 11, 2022 at 20:20

1 Answer 1

0

To Answer The first parst of your question you can map over this Array of Objects with this method for example using the .map method

React Code SandBox

MDN-.map() method JS

export const seasonOptions = [
  { value: 8471214, label: "198601987" },
  { value: 8471215, label: "198701988" },
  { value: 8471216, label: "198801989" },
  { value: 8471217, label: "198901990" },
  { value: 8471218, label: "199001991" },
  { value: 8471219, label: "199101992" },
  { value: 8471220, label: "199201993" },
  { value: 8471221, label: "199301994" },
  { value: 8471222, label: "199401995" },
  { value: 8471223, label: "199501996" },
];
    
//MAKE SURE TO MAP OVER THE <option></option> tag not the <Select/> 
//CHECK CODE SANDBOX FOR EXAMPLE IN PURE HTML5 AND REACT 
      {seasonOptions.map((option,index)=>
        <Select
        key={index}
        id="select"
        instanceId={"select"}
        options={option?.value}
        placeholder={option?.label}
        autoFocus
        value={select.value}
        onChange={handler}
      />
        
        )}

Check Out my Answer Here or for other examples here how to map over an array and access it values this method is just 1 of many .

How to find a value from array object in JavaScript? Stack Over Flow Question

For the Second Part Of the Question you can use the new SandBox

  • Steps
  1. Change the value property here from a string to a number by removing the quotation marks export const seasonOptions = [{value: 8471214, label: "198601987"},]

  2. Assign a useState hook to handle the active filtered item const [activeFilter, setActiveFilter] = useState([]);

3.Assign an arrow function to handle Filtering the Seasons using the setTimeOut() method setTimeout()-MDN-DOCS Where 500 is the time the function is executed for that time and

const handleSeasonsFilter = (item) => {
    setActiveFilter(item);

    setTimeout(() => {
      if (!item) {
        setFilterSeasons(item);
      } else {
        setFilterSeasons(
          seasonOptions.filter((season) =>
            seasonOptions?.includes(season?.label)
          )
        );
      }
    }, 500);
  };
  1. Pass that to url that searches the API url = `https://statsapi.web.nhl.com/api/v1/people/${activeFilter}/stats?stats=statsSingleSeason&season=200402005 Like in Line 65 in The Sand Box

  2. Display Them using useEffect() hook also add in the values in the dependency array or leave it empty to avoid infinite loops.

  useEffect(() => {
    //debug data
    console.log(stringDataDisplay);
    setActiveFilter(activeFilter);
    //DEBUG IF VALUE IF PASSED
    //setDatasearched(activeFilter);
  }, [
    /**EMPTY DEPENDENCY ARRAY TO AVOID INFINITE LOOPS */
    stringDataDisplay,
    activeFilter
  ]);

in My Example i Displayed Them using another useState Hook and State action
const [datasearched, setDatasearched] = useState([])

& Finally Just Assigned a new const stringDataDisplay = JSON.stringify([datasearched]); To Stringify the [datasearched] Array Here.

Note Make sure to pass the handleSeasonsFilter to OnClick as an empty arrow function and pass the option.value property as a String so the API Accepts the request.

Hope this helps with your Example and Ill try to Check the code sandbox also with your method.

Bear in Mind i still i am developing this and i understand you want the values of the seasons to be shown when no player id is selected Am i correct?

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you! The thing is I am looking to loop through this end point: statsapi.web.nhl.com/api/v1/people/8471214/… using season options to replace '20052006' then returning each result filtering out seasons where the splits array would be empty. I haven't used code sandbox before. Would I just import the whole code base?
So basically you want to filter out players by seasons ? and display that value using the value: prop mentioned in the seasonsOptions Array of Objects am i correct ? for the code sandbox question You would replicate it as much as you can with the parts you need for the question to minimize efforts , a swell for the steps for the sandbox 1 . sign up for codesandbox.io 2. select create from the navigation bar on the right 3. select start from a template and choose React 4. On the left tab you will find a dependencies installer , make sure to match those from your package.json file!
and display the results according to the people https://statsapi.web.nhl.com/api/v1/people/${props.playerId}/stats?stats=statsSingleSeason&season=${selected.value} player id and selected value as you mentioned here?
Yeah so I'm looking into two options. First, I could go the select route and filter out the particular season value from seasonOptions if the splits array is empty like here: statsapi.web.nhl.com/api/v1/people/8471214/… . The other way could be to loop through all the season options and filter out the seasons which splits is empty, then putting all the responses into a separate array and displaying each season in a table. I'm looking into creating a sandbox with the relevant code.
codesandbox.io/s/friendly-kapitsa-c97rzy?file=/components/… So for this example, this player only played seasons from 2005 onward. How would I go about removing the seasons from options prior to 20052006 which are null? This is only one example since in the full app, ID's are dynamic so players could have null values in x number of seasons.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.