简体   繁体   中英

how to get, by a get from axios, data in useState with react functionnal component

I'm working on react project generated by jhipster. When I perform a get request from my rest api.

GET http://localhost:8080/api/account
Accept: */*
Cache-Control: no-cache
Authorization: Bearer bearerValue

I get that answer:

HTTP/1.1 200 OK
Expires: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com data:
Date: Sun, 05 Apr 2020 18:26:07 GMT
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
Feature-Policy: geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'
Transfer-Encoding: chunked
Content-Type: application/json

{
  "id": 3,
  "login": "admin",
  "firstName": "Administrator",
  "lastName": "Administrator",
  "email": "admin@localhost",
  "imageUrl": "",
  "activated": true,
  "langKey": "fr",
  "createdBy": "system",
  "createdDate": null,
  "lastModifiedBy": "system",
  "lastModifiedDate": null,
  "authorities": [
    "ROLE_USER",
    "ROLE_ADMIN"
  ]
}

which means API is ok. My problem is how can I get the result from axios promise in my state, with just performing only one request.

Here is how I try to proceed.

portfolio.tsx


export interface IPortfolioProps extends StateProps,
  DispatchProps,
  RouteComponentProps<{ url: string }> {
}

export interface AccountState {
  id: number,
  login: string,
  firstName: string,
  lastName: string,
  email: string,
  imageUrl: string,
  activated: boolean,
  langKey: string,
  createdBy: string,
  createdDate: string,
  lastModifiedBy: string,
  lastModifiedDate: string,
  authorities: Array<string>
}

export const Portfolio = (props: IPortfolioProps) => {

  const currentAccountState = async (): Promise<AccountState> => {
    return await axios.get<AccountState>(`/api/account`)
      .then((response) => {
        return response.data
      });
  };

  // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
  // @ts-ignore
  const isAdmin: boolean = () => {
    let as: AccountState;
    currentAccountState()
      .then(response => {
        as = response;
        // eslint-disable-next-line no-console
        console.log('as : ', as);
        return as.authorities.find(
          authority => authority === AUTHORITIES.ADMIN) !== undefined;
      });
  };

  const [admin, setAdmin] = useState(isAdmin);

  return (
    <div>
      {`admin : ${admin}`}
    </div>);
}

when running the app I always have "admin: undefined" as result on the screen, while my console login show me the right account expected account. What I want is to save as state the boolean answer is current user is admin, in the admin state.

I think it's because there is no default value for admin , so admin is undefined when the page first renders before you get a response back from the API. It's better to initialize it with a default value first, call the API on mount, then update the state with the response.

You can try something like:

const [admin, setAdmin] = useState(null);

useEffect(() => {
    if (!admin) {
        const currentAccountState = async (): Promise<AccountState> => {
            return await axios.get<AccountState>(`/api/account`)
                .then((response) => {
                    return response.data
                });
        };
        currentAccountState()
            .then(response => {
                console.log('as : ', response );
                // probably add better handling here in the case that there is no result in the find, otherwise you mightrun into the same issue if admin is undefined again
                setAdmin(response.authorities.find(authority => authority === AUTHORITIES.ADMIN) !== undefined);
            });
    }
}, [admin])

return (
    <div>
        {`admin : ${admin}`}
    </div>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM