thanks for taking time and reading this question. I have a function called loginstatus(), it evaluates the login status, I want it to alter state below 👇. I don't know exactly where to place props, to be able to alter state. A brief description of where and why you did edits would be awesome, thanks in advance
const [count, setCount] = useState();
I have got everything else working I just want to find how change the state.
import { useEffect, useState } from "react";
import './App.css';
import 'semantic-ui-css/semantic.min.css'
import { Login } from './functions/login/login.js';
import { Logout } from './functions/login/logout.js';
import { loginstatus } from './functions/login/loginstatus.js';
import { currentloginid } from './functions/login/loginid.js';
import { ViewUser } from './functions/users/viewuser.js';
import { CreateUser } from './functions/users/createuser.js';
import { ViewAllUsersComponent } from './functions/users/viewallusers.js';
import { ViewQuestionComponent } from './functions/question/viewquestion.js';
function Process(props) {
console.dir(props.count);
if (props.count === "Logged In") {
return (
<>
<ViewUser />
<Logout setCount={props.setCount} />
<CreateUser />
<ViewAllUsersComponent />
<ViewQuestionComponent />
</>
);
} else {
return <Login setCount={props.setCount} />;
}
}
function App() {
const [count, setCount] = useState();
useEffect(() => {
loginstatus();
}, []);
return <Process count={count} setCount={setCount} />;
}
export default App;
export function loginstatus() {
fetch('http://localhost/gotaquestion/api/api.php?action=loginstatus',
{
method: 'GET',
credentials: 'include'
})
.then(function(response) {
if (response.status == 202) {
props.setCount("Logged In");
} else {
props.setCount("Not Logged In");
}
})
}
props is a special keyword in React, which stands for properties and is being used for passing data from one component to another. Your loginStatus
function is NOT a react component and does not have access to your Components props.
More about it here: https://reactjs.org/docs/components-and-props.html
To achieve what you want, you can pass a function as an argument to your loginStatus
function, that would look something like this:
More about functions and arguments here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
function App() {
const [count, setCount] = useState();
const loginSuccess = () => {
setCount("Logged In");
}
const loginFailed = () => {
setCount("Not Logged In");
}
useEffect(() => {
loginstatus(loginSuccess, loginFailed);
}, []);
return <Process count={count} setCount={setCount} />;
}
loginStatus.js
export function loginstatus(successCb, errorCB) {
fetch('http://localhost/gotaquestion/api/api.php?action=loginstatus',
{
method: 'GET',
credentials: 'include'
})
.then(function(response) {
if (response.status == 202) {
successCb();
} else {
errorCb();
}
})
}