Changing components state from a function in another fileUnderstanding unique keys for array children in React.jsUncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: objectUpdating Navigator component depending on state in ReduxHow to access parent component state in child component?React router not rerendering after state changeComponent state reverts back to default before correcting itself very fastReact-router - component reloads on parent component state change?React get props from another componentReact redirect not displaying correct componenthow to access login details from all components in reactjs
If Trump gets impeached, how long would Pence be president?
How to kill my goat in Goat Simulator
May a man marry the women with whom he committed adultery?
Is my investment strategy a form of fundamental indexing?
Am I allowed to use personal conversation as a source?
How to politely refuse a startup's equity?
How do I stop my characters falling in love?
Recommendations or Experiences on Archiving Mailing Data
What do I do with a party that is much stronger than their level?
What language is Raven using for her attack in the new 52?
How to get CPU-G to run on 18.04
Assuring luggage isn't lost with short layover
Isolated audio without a transformer
Issue with Expansions of Nested Macros
Heisenberg uncertainty principle in daily life
Why do planes need a roll motion?
How to avoid theft of potentially patentable IP when trying to obtain a Ph.D?
What is the difference between position, displacement, and distance traveled?
How do I explain an exponentially complex intuitively?
Why can't my huge trees be chopped down?
How did the Axis intend to hold the Caucasus?
Decreasing star count
Correlation length anisotropy in the 2D Ising model
Why did House of Representatives need to condemn Trumps Tweets?
Changing components state from a function in another file
Understanding unique keys for array children in React.jsUncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: objectUpdating Navigator component depending on state in ReduxHow to access parent component state in child component?React router not rerendering after state changeComponent state reverts back to default before correcting itself very fastReact-router - component reloads on parent component state change?React get props from another componentReact redirect not displaying correct componenthow to access login details from all components in reactjs
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm quite new in React and I don't really understand how to make this work. I'm trying to update App.js's user state with the information coming from MediaAPI.js. I've tried to create a method in App component and then call the method from MediaAPI.js with the JSON data in brackets, but it really isn't working. Any help will be greatly appreciated!
App.js
class App extends Component
state =
user: [],
;
updateUser = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
import App from '../App';
const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(json=>
console.log(json);
App.updateUser(json);
);
;
reactjs react-router
add a comment |
I'm quite new in React and I don't really understand how to make this work. I'm trying to update App.js's user state with the information coming from MediaAPI.js. I've tried to create a method in App component and then call the method from MediaAPI.js with the JSON data in brackets, but it really isn't working. Any help will be greatly appreciated!
App.js
class App extends Component
state =
user: [],
;
updateUser = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
import App from '../App';
const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(json=>
console.log(json);
App.updateUser(json);
);
;
reactjs react-router
add a comment |
I'm quite new in React and I don't really understand how to make this work. I'm trying to update App.js's user state with the information coming from MediaAPI.js. I've tried to create a method in App component and then call the method from MediaAPI.js with the JSON data in brackets, but it really isn't working. Any help will be greatly appreciated!
App.js
class App extends Component
state =
user: [],
;
updateUser = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
import App from '../App';
const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(json=>
console.log(json);
App.updateUser(json);
);
;
reactjs react-router
I'm quite new in React and I don't really understand how to make this work. I'm trying to update App.js's user state with the information coming from MediaAPI.js. I've tried to create a method in App component and then call the method from MediaAPI.js with the JSON data in brackets, but it really isn't working. Any help will be greatly appreciated!
App.js
class App extends Component
state =
user: [],
;
updateUser = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
import App from '../App';
const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(json=>
console.log(json);
App.updateUser(json);
);
;
reactjs react-router
reactjs react-router
asked Mar 26 at 18:57
H. JuhoH. Juho
225 bronze badges
225 bronze badges
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
This way App.updateUser(json);
only work when your method is static, and in a static method, you don't have access to this
, there are ways to achieve this:
1:
you can use your login function inside you App component like this :
class App extends Component
state =
user: [],
;
login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(data=>
this.setState(user: data);
);
;
componentDidMount(data)
this.login('username', 'password');
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
note:
and also you can simplify the login method by using Async/await like this :
login = async (username, password) =>
const response = await fetch(loginUrl,
method: 'POST', headers: 'Content-Type': 'application/json' ,
body: JSON.stringify(username, password)
);
const user = await response.json();
this.setState( user );
;
note:
and also you can do like this:
import login from 'MediaAPI.js';
class App extends Component
state =
user: [],
;
async componentDidMount(data)
const user = await login('username', 'password');
this.setState( user );
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
export const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json());
;
2:
you can create a component and on that component use App and set ref to it and then use updateUser
method.
---- there are other ways but I think those two are best.
add a comment |
As far as I know, I'd argue your approach is an anti-pattern. Below is how I'd approach it.
import mediaAPI from 'MediaAPI'
class App extends Component
state =
user: [],
;
// this is a React lifecycle hook that will be
// called when the component has mounted.
componentDidMount()
mediaAPI()
.then(res => res.json())
.then(this.setUserData)
setUserData = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55364466%2fchanging-components-state-from-a-function-in-another-file%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
This way App.updateUser(json);
only work when your method is static, and in a static method, you don't have access to this
, there are ways to achieve this:
1:
you can use your login function inside you App component like this :
class App extends Component
state =
user: [],
;
login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(data=>
this.setState(user: data);
);
;
componentDidMount(data)
this.login('username', 'password');
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
note:
and also you can simplify the login method by using Async/await like this :
login = async (username, password) =>
const response = await fetch(loginUrl,
method: 'POST', headers: 'Content-Type': 'application/json' ,
body: JSON.stringify(username, password)
);
const user = await response.json();
this.setState( user );
;
note:
and also you can do like this:
import login from 'MediaAPI.js';
class App extends Component
state =
user: [],
;
async componentDidMount(data)
const user = await login('username', 'password');
this.setState( user );
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
export const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json());
;
2:
you can create a component and on that component use App and set ref to it and then use updateUser
method.
---- there are other ways but I think those two are best.
add a comment |
This way App.updateUser(json);
only work when your method is static, and in a static method, you don't have access to this
, there are ways to achieve this:
1:
you can use your login function inside you App component like this :
class App extends Component
state =
user: [],
;
login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(data=>
this.setState(user: data);
);
;
componentDidMount(data)
this.login('username', 'password');
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
note:
and also you can simplify the login method by using Async/await like this :
login = async (username, password) =>
const response = await fetch(loginUrl,
method: 'POST', headers: 'Content-Type': 'application/json' ,
body: JSON.stringify(username, password)
);
const user = await response.json();
this.setState( user );
;
note:
and also you can do like this:
import login from 'MediaAPI.js';
class App extends Component
state =
user: [],
;
async componentDidMount(data)
const user = await login('username', 'password');
this.setState( user );
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
export const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json());
;
2:
you can create a component and on that component use App and set ref to it and then use updateUser
method.
---- there are other ways but I think those two are best.
add a comment |
This way App.updateUser(json);
only work when your method is static, and in a static method, you don't have access to this
, there are ways to achieve this:
1:
you can use your login function inside you App component like this :
class App extends Component
state =
user: [],
;
login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(data=>
this.setState(user: data);
);
;
componentDidMount(data)
this.login('username', 'password');
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
note:
and also you can simplify the login method by using Async/await like this :
login = async (username, password) =>
const response = await fetch(loginUrl,
method: 'POST', headers: 'Content-Type': 'application/json' ,
body: JSON.stringify(username, password)
);
const user = await response.json();
this.setState( user );
;
note:
and also you can do like this:
import login from 'MediaAPI.js';
class App extends Component
state =
user: [],
;
async componentDidMount(data)
const user = await login('username', 'password');
this.setState( user );
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
export const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json());
;
2:
you can create a component and on that component use App and set ref to it and then use updateUser
method.
---- there are other ways but I think those two are best.
This way App.updateUser(json);
only work when your method is static, and in a static method, you don't have access to this
, there are ways to achieve this:
1:
you can use your login function inside you App component like this :
class App extends Component
state =
user: [],
;
login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json()).then(data=>
this.setState(user: data);
);
;
componentDidMount(data)
this.login('username', 'password');
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
note:
and also you can simplify the login method by using Async/await like this :
login = async (username, password) =>
const response = await fetch(loginUrl,
method: 'POST', headers: 'Content-Type': 'application/json' ,
body: JSON.stringify(username, password)
);
const user = await response.json();
this.setState( user );
;
note:
and also you can do like this:
import login from 'MediaAPI.js';
class App extends Component
state =
user: [],
;
async componentDidMount(data)
const user = await login('username', 'password');
this.setState( user );
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
export default App;
MediaAPI.js
export const login = (username, password) =>
return fetch(loginUrl,
method: 'POST',
headers:
'Content-Type': 'application/json',
,
body: JSON.stringify(username, password)
).then(response => response.json());
;
2:
you can create a component and on that component use App and set ref to it and then use updateUser
method.
---- there are other ways but I think those two are best.
edited Mar 26 at 19:31
answered Mar 26 at 19:11
Mohammad RajablooMohammad Rajabloo
6255 silver badges11 bronze badges
6255 silver badges11 bronze badges
add a comment |
add a comment |
As far as I know, I'd argue your approach is an anti-pattern. Below is how I'd approach it.
import mediaAPI from 'MediaAPI'
class App extends Component
state =
user: [],
;
// this is a React lifecycle hook that will be
// called when the component has mounted.
componentDidMount()
mediaAPI()
.then(res => res.json())
.then(this.setUserData)
setUserData = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
add a comment |
As far as I know, I'd argue your approach is an anti-pattern. Below is how I'd approach it.
import mediaAPI from 'MediaAPI'
class App extends Component
state =
user: [],
;
// this is a React lifecycle hook that will be
// called when the component has mounted.
componentDidMount()
mediaAPI()
.then(res => res.json())
.then(this.setUserData)
setUserData = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
add a comment |
As far as I know, I'd argue your approach is an anti-pattern. Below is how I'd approach it.
import mediaAPI from 'MediaAPI'
class App extends Component
state =
user: [],
;
// this is a React lifecycle hook that will be
// called when the component has mounted.
componentDidMount()
mediaAPI()
.then(res => res.json())
.then(this.setUserData)
setUserData = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
As far as I know, I'd argue your approach is an anti-pattern. Below is how I'd approach it.
import mediaAPI from 'MediaAPI'
class App extends Component
state =
user: [],
;
// this is a React lifecycle hook that will be
// called when the component has mounted.
componentDidMount()
mediaAPI()
.then(res => res.json())
.then(this.setUserData)
setUserData = (data) =>
this.setState(user: data);
;
render()
return (
<Router>
<Nav/>
<Route exact path="/" component=Login/>
<Route exact path="/home" render=(props) => (
<Home ...props picArray=this.state.picArray/>
)/>
<Route exact path="/profile" component=Profile/>
<Route exact path="/single/:id" component=Single/>
</Router>
);
answered Mar 26 at 19:13
Anthony O'NeillAnthony O'Neill
576 bronze badges
576 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55364466%2fchanging-components-state-from-a-function-in-another-file%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown