0

I'm learning React and TypeScript and I am trying to write a login form, but after checking the user's data and creating the cookie, I want to rerender the parent component.

I have index.tsx (short version):

import React from 'react';
import ReactDOM from 'react-dom';
import cookie from 'react-cookies'

function Main() {
    let hmCookies = cookie.loadAll();
    console.log(hmCookies.auth);
    if (hmCookies.auth === 'true') {
        return (<Logout />)
    } else {
        return (<Login />)
    }
}
ReactDOM.render(<Main />, document.getElementById('root'));

and Logint.tsx:

import React from 'react';
import cookie from 'react-cookies'

const axios = require('axios');
class Login extends React.Component<any, any> {
  ...
  handleSubmit(event) {
    axios.post('http://localhost/php/Login.php', {
      login: this.state.login,
      password: this.state.password
    }, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .then(function (response) {
        if (response.data.auth == true) {
          cookie.save('auth', true);
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
  }
  render() { return ( <LoginFormHere /> ) }
}
export default Login;

After posting the user data in the form and making a request to PHP script via ajax, PHP returns a response. If it's true, save cookie. So, after changing cookie, I want to rerender component Main. However, I have no idea how to do this and I can't find any examples of this in the documentation.

How can this be achieved?

Kyle Dormer
  • 39
  • 10
xak2
  • 1
  • Pass a callback from `Main` to `child` and on your condition call this function. This function will internally call setState. Note, this is a basic version. Advance version would include a store and on response, you update data in it. This triggers `Main` and it updates components – Rajesh May 21 '19 at 12:53

1 Answers1

1

You can create a function in your Main component to serve to rerender. Let's call it - updateParent. Then you can pass updateParent function to your Login component as props and use it if response.data.auth == true. updateParent can be implemented as in the following question.

Here the example.

Also, you could use a stateful(class) component instead of functional. This allows you to use forceUpdate

melden
  • 11
  • 1
  • Thank you for your example, it's works fine. But in my case it's don't want work. I think this happens becouse my parent and child components in different files. When i try call updateParent from child using event - all is ok. But when i try call it from function in my child component, i got error: Line 85: Expected an assignment or function call and instead saw an expression no-unused-expressions. – xak2 May 23 '19 at 07:40
  • @xak2, This error looks somewhat as if you forgot parentheses when calling a function, i.e. `updateParent` instead of `updateParent()` – Iorweth333 Dec 09 '20 at 08:45