ReactJS: make a select that load all values from api - javascript

I'm creating a select (at the moment i'm using React-Select component) to retrive all the result from the api.
The problem is that API gives me back 20 values, so I should find a method to load other 20 values ( as I make another api call )
const option = personList && personList .map((spl) => {
return {
value: spl.perCod,
label: spl.perName
}
})
<Row>
<Col>
<Select
id="perCod"
name="perCod"
options={option}
/>
</Col>
</Row>
the personList is populated calling the api:
useEffect(() => {
sortEntities();
}, [paginationState.activePage, paginationState.order, paginationState.sort]);
const sortEntities = = () => {
//...
props.getFilteredEntities(
search, // i pass there the parameters for the research
paginationState.activePage - 1,
paginationState.itemsPerPage,
`${paginationState.sort},${paginationState.order}`
),
}
props.getFilteredEntities in my reducer is:
export const getFilteredEntities: ICrudSearchAction<Person> = (search, page, size, sort) => {
const params = new URLSearchParams(search) ? new URLSearchParams(search).toString() : null;
const requestUrl = `${apiUrl}${sort ? `?page=${page}&size=${size}&sort=${sort}` : ''}${sort ? '&' : '?'}${params}`;
return {
type: ACTION_TYPES.FETCH_PERSON_LIST,
payload: axios.get<Person>(`${requestUrl}${sort ? '&' : '?'}cacheBuster=${new Date().getTime()}`),
};
};
At the moment my select has the first 20 results from api. I should need to load others. How can I do? thank you.

change your <Select> code with this,
you have to add option tag within iteration, to render all options within select tag,
<Select id="perCod" name="perCod">
{option.map(o=><option key={Math.random()} value={o.perCod} >{o.perName}</option>)}
</Select>

Related

i want to Rerender antd select component default value on app language change

i am facing problem with antd select item. i am generating select item dynamically i am using default value to show checked/preDefined value but my app has mutilple language support so when i change my app language default value not changing. i am attaching screenshoots to give you full understanding enter image description here
here is my code snippest
<StyledSelectLarge
placeholder={item.settings_help_text}
defaultValue={preSelectDropDowns(item,syslanguage)}
onChange={(val) => {
const current = findSetting(item)
if(current)
{
const payload = {
id: current.id,
setting_option_id: val,
};
const updatedValues = values?.filter((item3) => item3?.id !== current?.id);
fieldValue('dropdownValues', [...updatedValues, payload])
}
touchedValue('dropdownValues', true);
}}
>
{item?.settingOptions?.map((item2) => (
<StyledSelectLarge.Option
key={item2?.id}
value={item2?.id}
item={item2}
>
{item2?.translation?.[0]?.translated_text}
</StyledSelectLarge.Option>
))}
</StyledSelectLarge>
You will have to replace defaultValue with value and set it inside onChange every time
function DropDown(props) {
const [dropDownValue, setDropDownValue] = useState(preSelectDropDowns(item, syslanguage));
return (
<StyledSelectLarge
placeholder={item.settings_help_text}
value={dropDownValue}
onChange={val => {
const current = findSetting(item);
if (current) {
const payload = {
id: current.id,
setting_option_id: val,
};
const updatedValues = values?.filter(item3 => item3?.id !== current?.id);
fieldValue('dropdownValues', [...updatedValues, payload]);
}
touchedValue('dropdownValues', true);
setDropDownValue(val) // We set the new value here
}}
>
{item?.settingOptions?.map(item2 => (
<StyledSelectLarge.Option key={item2?.id} value={item2?.id} item={item2}>
{item2?.translation?.[0]?.translated_text}
</StyledSelectLarge.Option>
))}
</StyledSelectLarge>
);
}

Pass Parameter To Algolia React Instant SearchBox

I am building a website with React and I am using algolia instantsearch on it. I have managed to create a search page which shows all results and filters by search. I want to use an external search input from a different page on the instant search.
What I would like is the search results page to appear already filtered by the search input parameter. I already create a page like (https://url/search/q=name) but the results page isn’t taking the parameter. The instant search displays all the results.
How can I achieve this? Any recommendations or links i can read will be appreciated.
My code looks like this :
import algoliasearch from "algoliasearch/lite";
var url_string = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search;
var url = new URL(url_string);
var q = url.searchParams.get("q");
const searchClient = algoliasearch(
"xxxxxxxxxx",
"xxxxxxxxxxxxxxxxx"
);
function BusinessesSection({ busData }) {
var stateMapping = {
stateToRoute(uiState) {
const indexUiState = uiState['Test'];
return {
query: indexUiState.query,
page: indexUiState.page,
// ...
};
},
routeToState(routeState) {
return {
['Test']: {
query: routeState.query,
page: routeState.page,
// ...
},
};
},
};
const Hit = ({ hit }) => (
<Item.Group divided key={hit.id}>
<Item fluid>
<Item.Header> {hit.name} </Item.Header>
<Item.Description> {hit.business_json.description} </Item.Description>
<Button onClick={() => { handleSingle(hit);}}> View More </Button>
</Item>
</Item.Group>
);
return (
<div>
<InstantSearch
searchClient={searchClient}
indexName="Test"
routing = {
stateMapping = function (uiState) {
return {
q: uiState['Test'].query,
}
},
stateMapping.routeToState = function (routeState) {
return {
query: routeState.q
}
}
}
>
</InstantSearch>
</div>
);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(BusinessesSection);
To have a default search in a search box, one can use the defaultRefinement parameter on the SearchBox widget of React InstantSearch.
You can add in here the value of your external search input, and then it will work out of the box.
<SearchBox
defaultRefinement={q}
translations={{
placeholder: "Search …"
}}
The defaultRefinement is a string

Problem rendering items in select (React js)

I am trying to load the options of a select depending on another select. I extract the data from an array (which will later have much more data).
My problem is that the second select loads the correct items BUT in a single options and not separately.
Any idea what I'm failing? I am a newbie in react. I apologize if the code is very horrible! Any help will be welcome.
P.S. I don't know if it makes any difference in this case, but I'm using "Ant Design".
import React, { useState } from 'react';
import { Row, Col, Form, Select, Input } from 'antd';
export default function SelectPetZone(props) {
const { publicationData, setPublicationData } = props;
const { Option } = Select;
const arrayZones = [
{
departmentName: "Montevideo",
neighborhood: ['Centro', 'Cordón', 'Flor de Maroñas', 'Manga']
},
{
departmentName: "Canelones",
neighborhood: ['Las Piedras', 'El Dorado', 'Progreso', 'La Paz']
}
];
const optionsDepartments = [];
const [optionsNeighborhood, setoptionsNeighborhood] = useState([]);
for(const item of arrayZones) {
optionsDepartments.push(<Option key={item.departmentName} value={item.departmentName}> { item.departmentName } </Option>);
}
const chargeNeighborhood = e => {
// Set department
setPublicationData({ ...publicationData, department: e });
let arrayDepartment = arrayZones.filter(function(i) {
return i.departmentName === e;
});
let arrayNeighborhood = arrayDepartment.map(function(i) {
console.log(i.neighborhood); // => Print array with correct values
return <Option key={i.neighborhood} value={i.neighborhood}>{i.neighborhood}</Option>;
})
setoptionsNeighborhood(arrayNeighborhood);
}
return (
<>
<Row>
<Col lg={6}>
<Form.Item>
<Select placeholder='Departamento' onChange={chargeNeighborhood} value={publicationData.department} >
{optionsDepartments}
</Select>
</Form.Item>
</Col>
<Col lg={6} offset={3}>
<Form.Item>
<Select placeholder='Barrio' onChange={e => setPublicationData({ ...publicationData, neighborhood: e })} value={publicationData.neighborhood} >
{optionsNeighborhood}
</Select>
</Form.Item>
</Col>
</Row>
</>
)
}
In chargeNeighbourhood function I also tried to do this but did not get a good result:
const chargeNeighborhood = e => {
// Set department
setPublicationData({ ...publicationData, department: e });
// Load neighborhood
for(const i of arrayZones) {
if(e === i.departmentName) {
for(const j of i.neighborhood) {
// console.log(j);
setoptionsNeighborhood([...optionsNeighborhood, <Option value={j} key={j}>{j}</Option>]);
}
}
}
}
Your problem is that you're mapping arrayDepartment inside changeNeighborhood and, if I understand your problem correctly, after you get the right department, you should be mapping arrayDepartment.neighborhood to map every neighborhood string into an Option.
For clarity, it would be a good idea to change that property name from neighborhood to neighborhoods since it's a list of neighborhoods.
In your comment, it seems like you already concluded that neighborhood is an array when you have this line:
console.log(i.neighborhood); // => Print array with correct values
So when you set your value for the Option component, you're actually passing an entire array:
<Option key={i.neighborhood} value={i.neighborhood}>{i.neighborhood}</Option>
That's why you're seeing all options as an array. Option is just converting that list into a string by concatenating every element of the array.

Reactjs - Passing API data as props for Autocomplete component (Material-UI)

I am a beginner in Reactjs. I am trying to implement the Autocomplete component provided by material-ui. I want to pass the API link as a prop to the element. But how to pass the json label name as a prop to be used in "getOptionLabel"? For example, If we consider this API link which returns TV Show names, we need to use SHOW.NAME to access the name of the show.
getOptionLabel={(option) => option.show.name}
Here, the dynamic part is 'show.name'. How to pass this as prop? I tried doing
const label = 'show.name'
and then
getOptionLabel={(option) => option.label}
But his wouldn't work.
You need to pass the props in the function.
You could do something like this:
export default function App() {
const someData = [{
name: "abc"
}]
return ( <
Autocomplete myOptions={someData} />
);
}
export default function ComboBox(props) {
return ( <
Autocomplete id = "combo-box-demo"
options = {
props.myOptions
}
getOptionLabel = {
(option) => option.name
}
style = {
{
width: 300
}
}
renderInput = {
(params) => < TextField { ...params
}
label = "Combo box"
variant = "outlined" / >
}
/>
);
}
See it live here

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?
On the top of my head, here's two solutions you may want to try:
Set each of you select's options as a tuple:
value={[item.league_id, item.team_id]}
or set each of you select's options' team_id and league_id as data-attributes
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);
};

Categories