ReactJs 'map' is Not a Function - javascript

I Try to make Github API fetch To get User GitHub info
componentDidMount() {
const { username } = this.props;
const { clientId, clientSecret, count, sort } = this.state;
fetch(
`http://api.github.com/users/${username}/repos?per_page=${count}&sort=${sort}&client_id=${clientId}&client_secret=${clientSecret}`
)
.then(res => res.json())
.then(data => {
if (this.refs.myRef) {
this.setState({ repos: data.conves });
}
})
.catch(err => console.log(err));
}
When I Start render it with map() I get an error that map() is not function!
const repoItems = repos.map(repo => (
<div>
<Link to={repo.html_url} className="text-info" target="_blank">
{repo.name}
</Link>
</div>
));
enter image description here

Related

How to add loader correctly while infinite scrolling?

I tried multiple ways to implement loading while fetching more data during infinite scrolling, but nothing worked properly, so I deleted loader; I have here state (with redux) named: loading but cannot write the logic of loading correctly. Could you please tell me how I can make it work?
Here I will provide with code:
import React, {useEffect} from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import {setAllUsers, setLoading, setPage} from '../redux/actions/actions';
import User from './User';
import '../styles/AllUsersList.css';
const AllUsersList = () => {
const allUsers = useSelector(state => state.setAllUsersReducer);
const page = useSelector(state => state.setPageReducer);
const loading = useSelector(state => state.setLoadingReducer);
const dispatch = useDispatch();
const fetchAllUsers = () => {
fetch(`${url}/${page}/15`)
.then(res => res.json())
.then(data => {
dispatch(setAllUsers(data.list));
})
.catch(err => console.log('Error message: ', err))
}
useEffect(() => {
fetchAllUsers();
}, [page])
const handleScroll = () => {
dispatch(setPage());
}
window.onscroll = function () {
if(window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) {
handleScroll();
}
}
return (
<div className="allUsersList">
{
allUsers ? (
allUsers.map((user, index) => (
<Link key={user.id} to={`/user/${user.id}`}>
<User name={user.name} lastName={user.lastName} prefix={user.prefix} title={user.title} img={user.imageUrl}/>
</Link>
))
) : (
<div> Loading... </div>
)
}
</div>
)
}
export default AllUsersList;
Your state loading would be set to true in your function fetchAllUsers the data and when the promise resolves it gets set to false.
Here's an example on how you would do it, you can adapt it to use a redux dispatcher to change loading state.
const loading = useState(false);
...
const fetchAllUsers = () => {
setLoading(true);
fetch(`${url}/${page}/15`)
.then(res => res.json())
.then(data => {
dispatch(setAllUsers(data.list));
})
.catch(err => console.log('Error message: ', err))
.finally(() => {
setLoading(false);
})
}
...
{
!loading ? (
allUsers.map((user, index) => (
<Link key={user.id} to={`/user/${user.id}`}>
<User name={user.name} lastName={user.lastName} prefix={user.prefix} title={user.title} img={user.imageUrl}/>
</Link>
))
) : (
<div> Loading... </div>
)
}

Sending data from parent to child prop returns a value then undefined functional component

In the main dashboard component i do get requests for 5 arrays. When I log them into the console i get the data.
When I try to pass down the data to a child component the values get undefined then values then undefined
The dashboard;
const [logdata, setLogData] = useState([])
const [storageData, setStorageData] = useState([])
const [logquotation, setLogQuotation] = useState([])
const [storageQuotation, setStorageQuotation] = useState([])
const [productQuotation, setProductQuotation] = useState([])
const getLogData = () => {
axios.get("http://localhost:8080/api/logisticsrecords")
.then(res => {
setLogData(res.data)
console.log(res)
})
.catch(err => console.log(err))
}
const getStorageData = () => {
axios.get("http://localhost:8080/api/storageshipment")
.then(res =>{
setStorageData(res.data)
})
.catch(err => console.log(err))
}
const getLogisticsQuotation = () => {
axios.get("http://localhost:8080/api/logisticsquotation")
.then(res =>{
setLogQuotation(res.data)
})
.catch(err => console.log(err))
}
const getStorageQuotation = () => {
axios.get("http://localhost:8080/api/storagequotation")
.then(res =>{
setStorageQuotation(res.data)
})
.catch(err => console.log(err))
}
const getProductQuotation = () => {
axios.get("http://localhost:8080/api/productquotation")
.then(res =>{
setProductQuotation(res.data)
})
.catch(err => console.log(err))
}
useEffect(() => {
getLogData()
getStorageData()
getLogisticsQuotation()
getProductQuotation()
getStorageQuotation()
}, [])
console.log("dashboard data",logdata, storageData, storageQuotation, logquotation)
At this point when i log all the states to the console i get the values as expected.
Passing the values as props to the child component
<DashboardHome
storage={storageData}
logistics = {logdata}
storeQuotation = {storageQuotation}
prodQuotation = {productQuotation}
logisticsQuotation = {logquotation}
/>
Destructuring the values at the child component
const DashboardHome = ({ storage, logistics, storeQuotation, prodQuotation, logisticsQuotation }) => {
console.log("The dashboard logistics/storage",storage, logistics)
console.log("the dashboard [quotation] data", storeQuotation, prodQuotation, logisticsQuotation)
console.log(storage, "storage data")
console.log("variable length is", storage)
return(...)}
What I get at the console

React .map not rendering

I've done a API call to get some datas then store it in an array and do a .map in the return
This is the code if you guys have any ideas it's been 2 hours that i'm stuck on this :(
import {useEffect, useState} from 'react';
import {useParams} from "react-router-dom";
import axios from "axios";
const CharacterScreen = () => {
const params = useParams()
const [character, setCharacter] = useState([]);
const [starships, setStarships] = useState([]);
useEffect(() => {
axios.get(`https://swapi.dev/api/people/?search=${params.character}`)
.then((r) => {
setCharacter(r.data.results[0])
getStarships(r.data.results[0])
})
.catch((e) => console.log(e))
const getStarships = (data) => {
let array = []
data.starships.forEach(element => {
axios.get(element)
.then((r) => {
array.push(r.data)
})
.catch((e) => console.log(e))
})
console.log(array)
setStarships(array)
}
}, []);
console.log(starships)
return (
<div>
<p>{character.name}</p>
<p>{character.eye_color}</p>
<p>{character.birth_year}</p>
<p>{character.gender}</p>
<p>{character.created}</p>
<p>{character.edited}</p>
{starships.map((element) => {
console.log('ok')
return (
<p key={element.key}>{element.name}</p>
)
})}
</div>
)
}
This is the .log of starships :
This is my return :
Any help would be apréciated
Use spread operator :
useEffect(() => {
axios.get(`https://swapi.dev/api/people/?search=${params.character}`)
.then((r) => {
setCharacter(r.data.results[0])
getStarships(r.data.results[0])
})
.catch((e) => console.log(e))
const getStarships = (data) => {
let array = []
data.starships.forEach(element => {
axios.get(element)
.then((r) => {
array.push(r.data)
})
.catch((e) => console.log(e))
})
setStarships([...array]) <=== //spread opeator
}
}, []);
The code inside your forEach will run asynchronously. You would have to wait for all that data to be actually populated in your array. async/await pattern + Promise.all(..) would be a good bet here and can be done like so :-
const getStarships = async (data) => {
let array = await Promise.all(data.starships.map(element => {
return axios.get(element)
.then((r) => {
return r.data
})
.catch((e) => console.log(e));
}))
setStarships(array);
}
Currently in your code by the time you do setStarships(array), array will be empty i.e. [].
Check this codesandbox where it's working :-
Note :- Don't pay attention to element.replace code, thats just for making secure requests
You have a syntax error, you should replace your bracket with a parenthesis like following:
{starship && starships.map((element) => (//here
console.log('ok')
return (
<p key={element.key}>{element.name}</p>
)
)//and here)}

API data not appearing in component but shows in console

I am making a rather simple API call to (https://api.punkapi.com/v2/beers) and displaying fetched data in the component, but somehow the data is not getting displayed on the page, but when I console log it the data is displayed correctly.
const Comp= () => {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
fetch('https://api.punkapi.com/v2/beers')
.then((res) => res.json())
.then((data) => {
setItem(data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div>
{item.map((beer) => {
const { name, tagline } = beer;
<p>{name}</p>;
console.log(name);
})}
</div>
);
};
Issue
You don't return anything from your item mapping. Return the JSX you want to render (i.e. return <p>{name}</p>) and don't forget to add a React key to the mapped elements. Below I've simplified to an implicit return.
You should also remove the console log from the render return as "render" methods are to be pure functions without side-effects, such as console logging. Either log the fetch result in the promise chain or use an useEffect hook to log the updated state.
useEffect(() => console.log(item), [item]);
...
return (
<div>
{item.map(({ id, name }) => (
<p key={id}>{name}</p>
))}
</div>
);
You need to return the value from inside .map method like:
return (<p>{name}</p>)
You need to return the JSX elements in your map.
const Comp= () => {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
fetch('https://api.punkapi.com/v2/beers')
.then((res) => res.json())
.then((data) => {
setItem(data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div>
{item.map((beer) => {
const { name, tagline } = beer;
return <p>{name}</p>;
console.log(name);
})}
</div>
);
};

External API issue in production - React.js

I build an app rendering data from an external API. In development mode everything works fine but in production the API doesn't load. It does't return anything not error in console.
axios.get("https://api.github.com/repos/....")
.then(response => ...)
.catch(error => console.log(error))
axios.get("https://api.github.com/...")
.then(response => {
....
})
.catch(error => console.log(error))
Can anyone tell me what the problem is?
You should check the network tab in the console and see which response code that request is returning. The catch block will only be hit if the response code of that request is one of these client errors listed on this website: https://httpstatuses.com/
Full code here
Note In development mode.
My signup form work fine, login work fine
But in production none of this work!
I have google during for one week but dont find answer.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import ShowCase from './utils/table.github.user';
import Validator from "../mm-admin/auth/auth.validator"
const Homepage = () => {
const [organisations, setOrgnisations] = useState([])
const [searchContributor, setSearchContributor] = useState('');
const [searchContributorResult, setSearchContributorResult] = useState([]);
const [isAdded, setAdded] = useState(false);
useEffect(() => {
let cleanup = false;
requestApi()
return () => {
cleanup = true;
}
}, [searchContributor])
const requestApi = () =>{
axios.get("https://api.github.com/repos/git/git/contributors", {
params : {
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
}
})
.then(response => {
const all = response.data;
const result = all.filter(contributor => {
return contributor.login.toLowerCase().includes(searchContributor.toLowerCase())
})
setSearchContributorResult(result)
})
.catch(error => console.log(error))
axios.get("https://api.github.com/organizations", {
params : {
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
}
})
.then(response => {
const all = response.data;
const result = all.filter(contributor => {
return contributor.login.toLowerCase().includes(searchContributor.toLowerCase())
})
setOrgnisations(result)
})
.catch(error => console.log(error))
}
const makeSearchContr = event => {
event.preventDefault()
setSearchContributor(event.target.value)
}
const addFavorite = (favorite, notes) => event => {
event.preventDefault();
if (Validator.isAuthenticated()) {
const id = Validator.isAuthenticated().user._id;
const favorites = {
item : JSON.stringify(favorite),
note : notes
}
axios.put("/user/action/" + id, favorites)
.then(res => {
setAdded(true)
const timer = setTimeout(() => {
setAdded(false)
}, 4000)
return () => clearTimeout(timer)
})
.catch(error => console.log(error))
} else {
console.log("Need to loged")
}
}
const contributorGit = () => {
return searchContributorResult.map((contributor, index) => {
return <ShowCase key={index} item={contributor} status={isAdded} favorite={addFavorite}/>
})
}
const organisationsGit = () => {
return organisations.map((organisation, index) => {
return <ShowCase key={index} item={organisation} favorite={addFavorite}/>
})
}
return (
<article>
<div className="">
<div className="container">
<form>
<div className="">
</div>
<div className="form-group">
<input type="text" className="form-control" placeholder="Search" value={searchContributor} onChange={makeSearchContr}/>
</div>
</form>
</div>
</div>
<div className="github-user" id="github">
<div className="container">
<h2>List contributor :</h2>
<ul style={{paddingLeft : '0px'}}>
{contributorGit()}
</ul>
<h2>List organisation :</h2>
<ul style={{paddingLeft : '0px'}}>
{organisationsGit()}
</ul>
</div>
</div>
</article>
)
}
export default Homepage;

Categories

Resources