Intermediate React Interview #
1: fetch Data
const [fetchData, setFetchData] = React.useState(null)
React.useEffect(() => {
fetch("https://randomuser.me/api/?results=20")
.then((response) => response.json())
.then((result) => {
setFetchData(result.results)
.catch(console.error)
}, [])
2: flatten location data
Compared to the method in this video, I used a different way. My data only convert array with object of location, but it made it like { header: { data key's name}, data{ ...array of location data}}
setFlattenLocation(
result.results.map((person) => {
return {
streetName: `${person.location.street.number} ${person.location.street.name}`,
city: person.location.city,
state: person.location.state,
country: person.location.country,
}
})
)
Here is my render code:
<table>
<thead>
<tr>
<th onClick={() => sortArray("city")}>City</th>
<th onClick={() => sortArray("state")}>State</th>
<th onClick={() => sortArray("country")}>Country</th>
</tr>
</thead>
<tbody>
{flattenLocation.map((element, index) => (
<tr key={index} className='personRow'>
<td>{element.city}</td>
<td>{element.state}</td>
<td>{element.country}</td>
</tr>
))}
</tbody>
</table>
3: sort the array when clicking the header name
It can't sort data yet, and it also needs adding a function that can toggle sorting way.
const sortArray = (sort) => {
setFlattenLocation((data) => {
return data.sort((a, b) => {
console.log(a[sort])
var nameA = a[sort].toUpperCase() // ignore upper and lowercase
var nameB = b[sort].toUpperCase() // ignore upper and lowercase
if (nameA < nameB) {
return -1
}
if (nameA > nameB) {
return 1
}
// names must be equal
return 0
})
})
}
4. search data values
const query = React.useRef('') // query value
getFilteredRow(flattenLocation, query).map() //render
Wild way:
However, it has some unwanted results when you typing "{" or header name.
function getFilteredRow(row, query){
return row.filter(row=> JSON.stringify(row).toLowerCase().includes(query))
}
"Better" way:
const getFilteredRows = (rows: any[], filterKey: string) => {
return rows.filter((row: any) => {
return Object.values(row).some((s) =>
("" + s).toLowerCase().includes(filterKey)
);
});
};