Home > Enterprise >  Typescript-React: array not visible as component
Typescript-React: array not visible as component

Time:10-19

todoApi.ts:

import axios, {AxiosResponse} from "axios";

const API_URL: string = "http://localhost:8080/api/v1/todo/";

export async function getTodos(filter: string): Promise<[]> {
    const response: AxiosResponse = await axios.get(API_URL, {
        headers: {
            filter: filter
        }
    });
    return await response.data;
}

Api response example:

[
    {
        "id": 1,
        "name": "Todo",
        "description": "Todo description",
        "done": false,
        "dateCreated": "2022-10-18",
        "deadline": "2022-10-19"
    },
    {
        "id": 2,
        "name": "Todo1",
        "description": "Todo1 description",
        "done": false,
        "dateCreated": "2022-10-18",
        "deadline": "2022-10-20"
    }
]

App.tsx: (excuse my bad naming conventions here)

import {getTodos} from "../api/todoApi";

let counter: number = 0;

export default function App(): JSX.Element {
    const [todos, setTodos] = useState([]);
 
    useEffect(() => {
        setInterval(() => {
            let _todos: ReactElement[] = [];

            getTodos(sessionStorage.getItem("search-key") as string).then((__todos) => {
                for (let i: number = 0; i < __todos.length; i  ) {
                    const todo = __todos[i];
                    _todos.push(
                        <Todo key={counter} id={todo["id"]} name={todo["name"]}
                              description={todo["description"]}
                              dateCreated={todo["dateCreated"]} deadline={todo["deadline"]}
                              done={todo["done"] === "true"}/>
                    );
                    counter  ;
                }
            });

            // @ts-ignore
            setTodos(_todos);
        }, 500);
    }, []);

    return (
        <>
            <div id={"todos"}>
                // some other components
                {todos}
                // some other components
            </div>
        </>
    );
}
  • The array of to-dos doesn't render although when going to react elements or logging the to-dos array I get the correct result.
  • Todo component just returns a div with class todo and an h1 for every prop.

CodePudding user response:

note: Storing your components in the state is a bad idea. Instead, store the data, and then map over the data to compose the components


Your issue is coming from the fact that you're loading the promise (.then) after you set your state (setTodos(_todos);) which means _todos is an empty array.

If you move the setTodos(_todos); below your for(){} loop, it will work. However, again, it is bad practice, and I urge you to continue research into better ways to do this :)

  • Related