0

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.
2
  • 1
    Storing components in the state is almost a bad idea. Do you get any errors? Commented Oct 18, 2022 at 18:03
  • @KonradLinkowski no i dont get any.about storing components in state, im new to react and i thought that was the only way for me to access todos from useEffect to update every 500ms, like i have it in the code sample Commented Oct 18, 2022 at 18:07

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that fixed the issue.regarding my bad practice, im kinda new to react and didnt know.ill make sure to look into it.thanks for the help!
@GeorgeAthans of course, not a problem :) hope you get far!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.