I have a problem list table with reactjs I have one worked code and not worked part. I want take datas from api and add an array for listing component the componetns are already designed and it has props are all true.
Let me explain:
Code Snippet:
import './App.css';
import React,{useState,useEffect} from 'react';
import {Container, Row} from 'reactstrap';
import Login from './components/Login';
import MainPage from './MainPage';
import WorkersPage from './WorkersPage';
import Schedule from './components/Schedule';
import Createrequest from './components/Createrequest';
import Jobrequests from './components/Jobrequests';
function getLocalObject(y)
{
var x;
x=localStorage.getItem(y);
return JSON.parse(x);
}
let array=[]
let requestArray=[]
function App() {
const [profile,setProfile]=useState('');
const [username,setUsername]=useState('');
const [requestedJobName,setRequestedJobName]=useState('');
const [requests,setRequests]=useState([]); //this is for requests
const [message,setMessage]=useState('')
const [password,setPassword]=useState('');
const [logout,setLogout]=useState(0);
const [allJobs,setAllJobs]=useState([]); //this is for all jobs
//This is for all jobs
useEffect(() => {
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("http://localhost/scheduleapp/api/schedule/all", requestOptions)
.then(response => response.text())
.then(result => {
setAllJobs(JSON.parse(result))
console.log('rs',result,'ls',allJobs)
})
.catch(error => console.log('error', error));
}, [])
// This is for requests (only admins!)
useEffect(() => {
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("http://localhost/scheduleapp/api/schedule/admin/requests", requestOptions)
.then(response => response.text())
.then(result => {setRequests( JSON.parse(result))})
.catch(error => console.log('error', error));
}, [])
function exit()
{
localStorage.clear()
window.location.reload(true);
}
//login function
const login = () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Allow-Origin","*");
myHeaders.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
var raw = JSON.stringify({username, password});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
//dsaasd
fetch("http://localhost/scheduleapp/api/personals/login", requestOptions)
.then(response => response.text())
.then(data =>{
localStorage.setItem('Logged',data);
})
.catch(error => console.log('error', error));
window.location.reload();
}
if(!getLocalObject('Logged'))
{
return( <div> <Login onSubmit={(e)=>e.preventDefault(e)} username={(e)=>setUsername(e.target.value)} password={(e)=>setPassword(e.target.value)} OnClick={()=>login() } /></div>
)
}
else{
if(getLocalObject('Logged').is_admin==1)
{
function accept()
{
}
function decline()
{
}
return (
<div>
{allJobs.map(item=>{
return (<Schedule approved_job_name={item.approved_job_name} approved_job_unique_id={item.approved_job_unique_id} approved_job_worker={item.approved_job_worker} date={item.date} />
)//it works great
} )
}
{
requests.map( item=>{
return(
<Jobrequests id={item.id}/>
)// this gives 'TypeError: requests.map is not a function'
} )
}
<button onClick={exit} className='btn btn-danger'>LogOut</button>
</div>
);
}
else{
function sendRequest()
{
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"requestedJobName": requestedJobName,
"uniquejobid": requestedJobName Date.now(),
"username": getLocalObject('Logged').username
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost/scheduleapp/api/schedule/worker/addrequest", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
return (
<div className='ms-4 mt-4'>
<Createrequest onSubmit={(e)=>e.preventDefault()} onChange={(e)=>setRequestedJobName(e.target.value)} onClick={sendRequest} />
{allJobs.map(item=>{
return (
<Schedule approved_job_name={item.approved_job_name} approved_job_unique_id={item.approved_job_unique_id} approved_job_worker={item.approved_job_worker} date={item.date} />
)
})}
<button onClick={exit} className='btn btn-danger'>LogOut</button>
</div>
);
}
}
}
export default App;
I want if logged user is admin user will see job requests and all jobs all jobs is listed success but requests give error "map is not a function" Best Regards Thanks from now...
Edit: Console Log Outputs:
useEffect(() => { fetch("http://localhost/scheduleapp/api/schedule/admin/requests") .then(response => setRequests(response.json()))
}, [])
Output: req []
useEffect(() => { fetch("http://localhost/scheduleapp/api/schedule/admin/requests") .then(response => setRequests(response.json())) }, [])
Output:
req
Promise {<fulfilled>: {…}}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
id: "1"
request_job_current_date: "2021-10-05"
request_job_name: "sdasdads"
request_job_unique_id: "sdasdads1633453239"
request_job_worker_uname: "dariustheone"
[[Prototype]]: Object
CodePudding user response:
Since requests
initial state is an array and that there is only one setRequest
, your problem is coming from the data your are passing to
.then(result => {setRequests( JSON.parse(result))})
Check what's in result
and also it's quite weird that you call .text() instead of .json() since you use JSON.parse.
But anyway your problem is coming from the content of result
which doesn't seem to be an array
CodePudding user response:
I think you should make sure that the fetch request to '/scheduleapp/api/schedule/admin/requests' return an array after you parse it. The error happen when you try to map something that is not an array.
CodePudding user response:
Your issue comes from the fact that requests
' array type got somewhat altered by your useEffect()
.
I suggest doing this instead:
fetch("http://localhost/scheduleapp/api/schedule/admin/requests", requestOptions)
.then(response => response.json())
.then(data => setRequests(data))
As long as your console.log(requests)
doesn't display a proper array
(yours seems to be an object) then your issue would persist.
P.S. Since GET
is the default method for fetch
, I believe that specifying it on requestOptions
isn't needed.