user19568466
user19568466

Reputation: 11

Typescript and data retrieval

My goal is to make an application that can retreive data from a mySQL database and have that parsed and displayed onto the page. I am utilizing Typescript and React for this. Here is the issue with code step by step.

I define an interface to ensure the data full fills a certain criteria.

interface QuizStructure{
name: string,
age: number,
favoriteHobby: string
}

Now technically the information in the database should conform to this interface since I'm uploading info that only full fills the criteria in the first place but Typescript doesn't know that when it retrieves the information.

Here I try to fetch the data from the database. Typescript rightly throws an error saying the data may not fullfill the 'QuizStructure' interface.

   const [data, setData] = useState<QuizStructure[]>([]) 

   function databaseFetch(){
       const prevRes = fetch('/api/quizFetch')
            .then(data=> data.json())
            .catch(err => console.log('error with data collection,', err));
            setData([...prevRes]);
   }

Easy solution is to just change 'useState<QuizStructure[]>([])' to 'useState<any[]>([])', but that defeats the purpose of Typescript. Is there a method to go about assuring Typescript that the data will fit the interface, or should I go about this approach in a completely different way?

Upvotes: 0

Views: 830

Answers (1)

mahpgnaohhnim
mahpgnaohhnim

Reputation: 63

Maybe try this

function databaseFetch(){
       fetch('/api/quizFetch')
            .then(data=> data.json())
            .then((res:QuizStructure[]) => {
                 setData([...res])
            })
            .catch(err => console.log('error with data collection,', err));
   }

Upvotes: 1

Related Questions