getting empty arrays when making a get request using axios - javascript

Hi :) I'm trying to get an array of numbers from my api that returns me something like: [{"numbers":[9,7,56,58,48,18],"gameId":1},{"numbers":[3,8,10,60,35,5],"gameId":2},{"numbers":[39,24,33,26,48,55],
I'm using axios and everytime I make a request this is what happens: [] length: 0 [[Prototype]]: Array(0)
this is my code:
const[game,setGame]= React.useState([]);
var[myGameNumbers, setMyGameNumbers]=React.useState([]);
React.useEffect(()=>{
axios.get("http://localhost:8080/games/game12").then((response)=>{
setGame(response.data);
});
}, []);
if (!game) return null;
function mappingNumbers(){
game.map((game) => (
setMyGameNumbers==game
));
if(!myGameNumbers) return null; else console.log(myGameNumbers);
}
this is the button that triggers the function:
<a href="#" className="button" onClick={mappingNumbers()}>
<p className="bttn-p">GERAR NÚMEROS</p>
</a>
I'm looking for a way to bring my array numbers, like this: [9,7,56,58,48,18] everytime I click on the button. If anyone knows how to help I'd be thankful :D
this is my full code if theres anything I've left out: https://github.com/vitoriaacarvalho/jogando-na-mega-sena/tree/main/front/jogando-na-mega

In your mappingNumbers you map over the game and do some check == against the setMyGameNumbers function which will not work. The correct syntax will be something like setMyGameNumbers(game)
You also check if myGameNumbers does not exist but it will always exist since the initial value is an empty array [] this is why the console.log logs an empty array.
...
if (!game) return null;
// will log everytime when a state gets updated
// and if the above statement is false
console.log("myGameNumbers", myGameNumbers);
function mappingNumbers() {
if (game.length < 1) return null;
setMyGameNumbers(game);
}
Updated the onClick with a correct syntax
<a href="#" className="button" onClick={() => mappingNumbers()}>
<p className="bttn-p">GERAR NÚMEROS</p>
</a>

Related

React - console logs empty an array and then logs a populated array after a second button click

I am running into a slight problem with using React and its hooks. I am trying to print out an array from an API, but it first prints as an empty array to the console, and then only when I click the button again does it prints the array.
Here is the function I'm using to make the array from API data:
const getChampion = () => {
for(let i = 0; i < getData.length; i++){
let individualChamp = champPeep.current.value;
if(getData[i].Name === individualChamp){
// console.log(getData[i]);
setShowChampion(individualChamp);
setChampionTitle(getData[i].Title);
let hitPoints = getData[i].Hp
let attack = getData[i].Attack;
let defense = getData[i].Defense;
let attackRange = getData[i].AttackRange;
let armor = getData[i].Armor;
setRadarData([hitPoints, attack, defense, attackRange, armor]);
console.log(radarData) //returns empty array don't know why
}
} //! Have to click search twice to update array to new array
} //Get Champion name and check to see if it is found in the API
Here is the button the input field that I assigned to this function:
return(
<div>
<div className='search'>
<input ref={champPeep} type="search" id='champion-search' placeholder='e.g Annie' />
</div>
<button onClick={getChampion} className='btn-prim'>Search</button>
</div>
)
And this is what is being logged to the console when I click on button btn-prim:
[]
And when I click the btn-prim button again this is then logged (which is correct):
(5) [524, 2, 3, 625, 19]
Is there something I'm doing wrong?
setState is asynchronous in react, so when you try to log radarData immediately after setRadarData it displays previous data stored in radarData. You can use useEffect hook to log current radarData state
useEffect(() => {
console.log(radarData)
}, [radarData])
why React setStates are async : Why is setState in reactjs Async instead of Sync?
I suggest that instead of you using
console.log(radarData) //returns empty array don't know why
try to add the useEffect hook to log the value of radarData whenever it changed.
Use something like:
useEffect(() => {console.log(radarData)}, [radarData])
State updates will reflect in their next rerender and not immediately. This has already been solved.
Basically your
setRadarData([hitPoints, attack, defense, attackRange, armor]);
console.log(radarData) //returns empty array because its still using the default state {}.
Refer to The useState set method is not reflecting a change immediately.

Skipping undefined elements from an API call

I am gathering data from an API to show the Pokemon typing. Some Pokemon have one type, while others have two.
The variables to gather the typing data are as such.
function createPokemonCard(pokemon) {
const type = pokemon.types[0].type.name;
const second_type = pokemon.types[1].type.name;
...}
And then I call them via InnerHTML in the same function with the following code.
<small class="type"><span>${type}/${second_type}</span></small>
Predictably, when it hits undefined for a Pokemon, it breaks and doesn't display the card. However I am not sure how to get it to not print the second type when it's undefined.
I thought about doing an if statement, but what should I call if there is an undefined variable?
function undefined {
if(second_type === 'undefined') {
???
}}
Or would a for loop work better? I am not sure how to get it to bypass the undefined and print nothing.
const second_type = pokemon.types[1] ? pokemon.types[1].type.name: undefined;
`<small class="type"><span>${type}${second_type!=undefined ? `/${second_type}`: ''}</span></small>`
The ? : syntax is a ternary operator (mdn)
It's a less verbose way of writing out the following:
if (second_type!=undefined) { // check if second_type is not undefined
return `/${second_type}` // if it's not return / and the second type
} else { //otherwise
return '' // return an empty string
}
If you do not want to display the trailing / when second_type is not defined one way to go could be
const type = pokemon.types.map(({ type }) => type.name).join("/")
and then
<small class="type"><span>${type}</span></small>

useState() in react does not update the data - is this the sort() issue?

when I click on the button to sort the data about countries after the website is loaded then the data displays correclty. But when I want to sort it again by different value, the data doesn't update and the state also doesn't update, however, the function works well, as I can see that the results in the console are sorted correctly. What can be the reason for this weird behaviour? Thank you for your time.
function AllCountries({ countries }) {
const [sortedCountries, setSortedCountries] = useState([]);
useEffect(() => {
console.log(sortedCountries)
}, [sortedCountries])
const sortResults = (val) => {
let sortedResults = countries.sort((a, b) => {
if (val === "deaths") {
return b.TotalDeaths - a.TotalDeaths;
} else if (val === "cases") {
return b.TotalConfirmed - a.TotalConfirmed;
} else if (val === "recovered") {
return b.TotalRecovered - a.TotalRecovered;
}
});
console.log(sortedResults);
setSortedCountries(sortedResults);
};
return (
<div className="all-container">
<p>Sort countries by the highest number of:</p>
<button onClick={() => sortResults("deaths")}>Deaths</button>
<button onClick={() => sortResults("cases")}>Cases</button>
<button onClick={() => sortResults("recovered")}>Recoveries</button>
<ul className="all-countries">
{sortedCountries.map((country, key) => {
return <li key={key}>{country.Country}</li>;
})}
</ul>
</div>
);
}
export default AllCountries;
Array.sort() method doesn't return new reference, it returns the same reference. So I assume in sortedCountries state is stored the same props.countries reference, that is why second button click doesn't set the state (it is the same reference), I can give you simple solution just change this line setSortedCountries(sortedResults) with this setSortedCountries([...sortedResults]) in this case copy of the sortedResults will be passed to setSortedCountries (new reference).
let sortedResults = countries.sort
this line is sorting the countries props and setting sortedResults to that pointer
Let us assume that pointer is held at mem |0001| for simplicity
After your first click, the function is fired, the prop is sorted, and sortedResults is set via setSortedCountries (set state).
This fires off the render that you desire, because the previous state was undefined, and now the state is pointing to |0001|
When your function runs again, the sort function fires off, does its work on |0001| and returns -- you guessed it -- |0001| but with your new sorted array.
When you go to set the state a second time, there wasn't actually any state changed because the previous country is |0001| and the country you want to change to is |0001|
So what can we do my good sir?
First I need you to think about the problem for a second, think about how you could solve this and try to apply some changes.
What you can try to do is copy the countries props to a new array pointer with the same values, and then sort it, and then set sortedCountries state to that list.
Does that make sense?
By the way, this is for similar reasons why if you try to setState directly on an new object state, the new object state will be exactly equal to the one you set. There isn't any real magic going on here. React does not automagically merge your previous object state and your new one, unless you tell it explicitly to do so.
In some sense you have told react to check differences between two states, an old country and a new country state (behind the scenes with the Vdom), but to react, those two states have no difference. And since the two object states have no difference, there will be no actual DOM changes.
You setting a pointer twice will therefore produce no actual changes.
You must therefore set state to an actual new pointer with new values, so the react virtual dom can compare the two states (the previous countries list) and the new countries list.
Hope that helps
-
It's a bit problem in React and another solution is by using the useReducer instead. such as below:
function reducer(state, action) {
return [...state, ...action];
}
function AllCountries({ countries }) {
const [sortedCountries, setSortedCountries] = useReducer(reducer, []);
useEffect(() => {
console.log(sortedCountries)
}, [sortedCountries])
const sortResults = (e, val) => {
e.preventDefault();
let sortedResults = countries.sort((a, b) => {
if (val === "deaths") {
return b.TotalDeaths - a.TotalDeaths;
} else if (val === "cases") {
return b.TotalConfirmed - a.TotalConfirmed;
} else if (val === "recovered") {
return b.TotalRecovered - a.TotalRecovered;
}
});
console.log(sortedResults);
setSortedCountries(sortedResults);
};
return (
<div className="all-container">
<p>Sort countries by the highest number of:</p>
<button onClick={(e) => sortResults(e, "deaths")}>Deaths</button>
<button onClick={(e) => sortResults(e, "cases")}>Cases</button>
<button onClick={(e) => sortResults(e, "recovered")}>Recoveries</button>
<ul className="all-countries">
{sortedCountries.map((country, key) => {
return <li key={key}>{country.Country}</li>;
})}
</ul>
</div>
);
}
export default AllCountries;

Unable to render an array of values (React component)

I am building a test app to learn more about React and I have made an API call which gets a huge JSON object.
I was able to break this json into the parts that I need and now I have 10 arrays of 3 props each. I am able to send these 10 arrays in 3 props to another component, which needs to use these 3 props 10 times and render a div class Card each.
I can console.log(this.props) and it shows 10 different arrays with 3 props each,however, I cannot produce a same element 10 times.. I tried using map() but since my array is initially undefined, map() is not able to function properly either. Is there any thing in react like *ngFor in Angular ?
What is the best way to go about this?
*EDIT
Here's more code guys. Sorry still noobie here..
ERROR : this.props.map is not a function
return(
<div>
{this.props.map((data,i)=>{
return(
<li key={i}>{data.likes}</li>
);
*EDIT 2
Soo I tried running map function with an if condition but the code still breaks the very moment the condition gets true..
render() {
if(this.props.url !== undefined){
this.props.map((data,i) =>{
return <li key={i}>{data.likes}</li>
})
}
My state method is :
state = {
userId: undefined,
likes: undefined,
url: undefined
}
and im setting my values on each data stream as follows :
const pics = await fetch(`${base_url}?key=${api_key}&q=${query}
&img_type=photo&per_page=12`).then(response => {
return response.json();
})
pics.hits.map((data) =>{
return this.setState({
userId: data.user_id,
likes: data.likes,
url: data.webformatURL
})
})
this.props won't have map, it's not an array. It's an object with a property for each property passed to your component. For instance:
<YourComponent foo="bar"/>
...will have this.props.foo with the value "bar".
So if you're passing an array to your component, like this:
<YourComponent theArrayProperty={[{likes: 42},{likes:27}]} />
...then you need the name of that property:
return (
<div>
{this.props.theArrayProperty.map((data,i) => {
return (
<li key={i}>{data.likes}</li>
);
})}
</div>
);
Side note: You can use a concise arrow function for the map callback instead:
return (
<div>
{this.props.theArrayProperty.map((data,i) => <li key={i}>{data.likes}</li>)}
</div>
);
...and no need for the () if you put the opening tag on the line with return (you can't leave off the ( if it's on the next line, but you probably knew that):
return <div>
{this.props.theArrayProperty.map((data,i) => <li key={i}>{data.likes}</li>)}
</div>;
...but that's a matter of style.
With little information that you have provided, my guess is that code fails at map() when you try to use it with undefined value.
Try adding a conditional check to render
{props && props.map([RENDER CODE HERE])}
You can just make simple if statement to check if the array is not undefined, and then pass it to map function.
Another option is to set a defaultProps for an empty array.
MyComponent.defaultProps = {
arrProp: []
};

React JS - How does this function work to delete JSON data?

I hope you can help.
I can't remember where I got the the snippet of code in the deleteHandler function. It deletes the relevant listdata item from the JSON array and re-renders as expected. I just don't understand what it's doing. Is it specific React syntax? Is it rudimentary stuff that I am oblivious to?
I know the state.listdata.splice(id, 1); line gets the current JSON object, but what does the arrow function do? What is being returned? I'm quite baffled by it.
Any help is much appreciated.
var AppFront = React.createClass({
getInitialState:function(){
return{
listdata: [
{"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
{"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
}
},
deleteHandler: function(e,id){
this.setState(state => {
state.listdata.splice(id, 1);
return {listdata: state.listdata};
});
},
render: function(){
var listDataDOM = this.state.listdata.map((item,index) => {return (<li key={item.id}>
{item.name}
<button onClick={()=>this.deleteHandler(item.id)}>delete</button>
</li>)});
return(
<div>
<h1>To-do List</h1>
<ul>
{listDataDOM}
</ul>
</div>
);
}
});
ReactDOM.render(<AppFront />,document.getElementById("container"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
1) About setState
setState function in React looks something like that :
setState(partialState, callback)
Where partialState may be : object , function or null.
In your particular case you use function, which returns an object of state variables.
setState(function(state){ return {some:data} })
and with arrow func (es6) , the same will look like
setState(state=> { return {some:data} })
in yout particular case arrow func used just for short
2) About splice
In handler, you use JS func splice() to remove element from state's array;
But it is bad practice, because it mutates the state of component.And It will cause bugs, problems and unpredictable behavior. You shouldn't mutate your state!
To avoid that you can copy your array through slice(), because slice returns new array.
var newArray = state.listdata.slice()
newArray.splice(index, 1);
3) About deleteHandler and data structure
deleteHandler doesnt work properly, and works only for first position.And if your data will look like that:
listdata: [
{"id":52,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
{"id":11,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
It will not work at all
For proper result , you should change deleteHandler to this:
deleteHandler: function(e,id){
//find index of element
var index = this.state.listdata.findIndex(e=>e.id==id);
//copy array
var newAray = this.state.listdata.slice();
//delete element by index
newAray.splice(index, 1);
this.setState({listdata: newAray});
},
and button
<button onClick={e=>this.deleteHandler(e,item.id)}>delete</button>
> JSBIN example
or you can delete by index
deleteHandler: function(e,index){
//copy array
var newAray = this.state.listdata.slice();
//delete element by index
newAray.splice(index, 1);
this.setState({listdata: newAray});
},
<button onClick={e=>this.deleteHandler(e,index)}>delete</button>
> JSBIN example
In your AppFront component you have a state
{
listdata: [
{"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
{"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
}
It represents initial data in your component. Every time you change state, your component gets rerendered.
You can change state by calling component's setState method
In deleteHandler
deleteHandler: function(e,id){
this.setState(state => {
// state.listdata - array of initial values,
state.listdata.splice(id, 1);
return {listdata: state.listdata}; // returns a new state
});
}
state.listdata.splice(id, 1) // removes an element with index == id from the array. You should not confuse listdata item.id and item index. In order for your code to work correctly you need to pass index in you deleteHandler.
<button onClick={()=>this.deleteHandler(index)}>delete</button>
Another thing is that you call deleteHandler only with one argument - item index so in your definition it should be
deleteHandler: function(index){
this.setState(state => {
// state.listdata - array of initial values,
state.listdata.splice(index, 1);
return {listdata: state.listdata}; // returns a new state
});
}
In your render method you iterate through this.state.listdata and return React.DOM nodes for each.
When you update component's state it gets rerendered and you see that item was deleted.
This code is written in es2015 so if it's new to you, it's better to start from reading something about new syntaxis.
state.listdata.splice(id, 1) deletes 1 element with the index equal to id from listdata array. For example if id equals to 0, then, after applying state.listdata.splice(id, 1), state.listdata will become:
listdata: [
{"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
And exactly this array will be returned by this arrow functions.
Keeping in mind, that splice method receives index as first argument, but you pass id property there, most probably you should change this code:
<button onClick={()=>this.deleteHandler(item.id)}>delete</button>
To:
<button onClick={()=>this.deleteHandler(index)}>delete</button>

Categories