Search code examples
javascriptreactjsreduxget

React Reduct - Select Onchange get method request


I have the following situation, i provide the a codesandbox demo to demonstrate my existing problem.

A bit of explanation about and how to reproduce the case

I am here in the component League.js, any league in the list has a link

<a href={`#${item.league_id}`} onClick={(e) => onClick(e, item.league_id)}>

  const onClick = (evt, id) => {
    evt.preventDefault();
    getDetail(id)
  };

The onclick function populates in the Details.js component the select options with the names of the teams. You can see below.

  if (teamsDetail.length) {
    details = (
      <select value={selectedOption} onChange={selectTeamStat}>
        {teamsDetail && teamsDetail.length > 0
          ? teamsDetail.map(item => (
              <option key={`${item.team_id}`} value={item.team_id}>
                {item.name}
              </option>
            ))
          : null}
      </select>
    );
  }

This is now the problem i have in Detail.js component, when i select the team name in my select i want send a get request getStats where i have to set two parameters ( team_id and league_id )

Here the relevant code

const [selectedOption, setSelectedOption] = useState("");

  const selectTeamStat = evt => {
    const { value } = evt.target;
    setSelectedOption(value);
    getStats(357, value);
  };

At the moment i can only pass the team_id which is the select value selectedOption

How can i also pass the league_id parameter?

I have hardcoded now putting 357 but i need to use the parameter league_id. How can i pass it from League.js Component?


Solution

  • I have figured it out how to pass the leagueId state

    These the steps i have done

    In the reducers/index.js i have created an initial state

    RECEIVE_LEAGUE
      league:[],
    
    case RECEIVE_LEAGUE:
      return {...state, leagueId: action.json};
    

    In the actions/index.js

    export const receivedLeague = json => ({
      type: RECEIVE_LEAGUE,
      json: json
    });
    

    I have added a dispatch in the getTeamsDetailById(id)

    dispatch(receivedLeague(id));
    

    In the Details.js component

    I have added the state leagueId on top

    and edited my selectTeamStat function

      const [selectedOption, setSelectedOption] = useState('');
    
      const selectTeamStat = (evt) => {
         const { value } = evt.target;
         setSelectedOption(value)
         getStats(leagueId, value);
      };