0

I'm new reactjs I'm trying to save data that I got from server like object(array) but I can't.

demo

at render() function, what should I do to save data, I don't wanna display, just save to users (array) or something? I think that I should use "map" but I don't know how to do. Next, I wanna save users to model.data like this. help me.

demo2

dance2die
  • 35,807
  • 39
  • 131
  • 194
Simpa407
  • 11
  • 1
  • 2

2 Answers2

0

Since you just started using react, try using React Hooks instead of class style components. It's the recommended way.

If you just want to store the data without displaying anything you need somekind of a encapsulated/shared state. For example redux or context can help you with that. Since context is in-built and easier to use, here is an example:

First create a context

users-context.js

import React from "react";

export const UsersContext= React.createContext();

Now create a custom hook to store your state.

useUsers.js

import React, {useState, useEffect} from "react";
export const useUsers = () => {
  const [users, setUsers] = useState([]);

  const getUsers = () =>{
    //your fetch
  }

  useEffect(()=>{ //equivalent to componentDidMount
    getUsers();
  }, [])

  return {users, setUsers}
}

Then provide the context so every component in your app has access to that context.

App.jsx

import {UsersContext} from "./UsersContext";

const App = () => {

const contextValue = useUsers();

return (
    <div className={'App'}>
      <UsersContext.Provider value={contextValue}>
        <Main/>
      </UsersContext.Provider>
    </div>
   );
 };

 export default App;

If you want to use the state in a component, e.g. a profile page do this:

profile-page.jsx

import React, {useContext} from "react";
import {UsersContext} from "./UsersContext";

const ProfilePage = () => {
const {users} = useContext(UsersContext);

// now you can use it like
console.log(users)

return (...) 
}
oemera
  • 3,223
  • 1
  • 19
  • 33
  • thanks so much for your help^^ but it doesn't work, maybe I'm wrong, can you help me again? My code is here: http://codepad.org/HL9vjlCv – Simpa407 Dec 02 '19 at 14:17
  • You are not doing what I did. You are still using classes. :) You should use functional components with hooks. Read more aboute hooks here: https://reactjs.org/docs/hooks-intro.html . You can copy paste almost everything I've posted. – oemera Dec 02 '19 at 14:29
0
import { UsersContext } from './Components/usersData/users-context';
const getUsers = () => {
  const {users} = UsersContext(UsersContext);
  console.log(users);
  return users;
}
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
            data:[]
        }
    data.push(getUsers);`
    }
  }
Simpa407
  • 11
  • 1
  • 2