Using Vue to Navigate Through JSON Responses

I am working with an API that provides a JSON response structured like this:

{
    "Thriller": "Thriller books",
    "Biographical": "Biographical books",
    "Romance": "Romance books"
}

My goal is to create routes that look like this:

http://example.com/thriller
http://example.com/biographical
http://example.com/romance

The API will determine the types of books available to view, and then a component called Books will display general information about each book type. I have made progress with my router setup:

import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';
import Books from './views/Books.vue';

Vue.use(Router);

var books: Record<string, string> = await fetch('http://example.com/api/available-books')
    .then((response) => response.json())
    .then((data) => {
        return data;
    });


export default new Router({ 
    mode: 'history',
    base: process.env.BASE_URL,
    routes: books.map((shortname: string, fullname: string) => ({ component: Books, path: `/${shortname}` })),
});

However, the TypeScript linter is flagging two issues with the map() function: TS1005: comma expected at the end of the line and

TS2349: Cannot invoke an expression - type String has no invocation signature
. I am unsure of how to address these problems. Is there a more effective approach I should consider? I am still new to single-page application development.

Answer №1

If you're looking to optimize the routes for the route you're on, here's a more streamlined approach to generating them.

const genres = {
    "Thriller": "Thriller books",
    "Biographical": "Biographical books",
    "Romance": "Romance books"
}

const routeMap = Object.entries(genres).map(genre => {
  const [shortname, fullname] = genre
  return { component: 'Books', path: `/${shortname.toLowerCase()}` } 
})

console.log(routeMap)

Alternatively, I suggest utilizing dynamic route matching to pass the book ID into the component rather than making a synchronous API call on page load.

const router = new VueRouter({
  routes: [
    { path: '/book/:shortname', component: Book }
  ]
})

Answer №2

Upon reviewing the structure of your json data, it appears that the issue with the map function not working is due to the fact that the data is in the form of a large object, whereas map function is designed to work with arrays.

There are two possible solutions to address this. One option is to reformat the json data into an array, like this:

{
    "Thriller": "Thriller books",
    "Biographical": "Biographical books",
    "Romance": "Romance books"
}
const mappedToArray  = [];
for (const prop in json) {
    mappedToArray.push({[prop]:json[prop]});
}
console.log(mappedToArray) 
// output is:> Array [
//Object { Thriller: "Thriller books" },
// Object { Biographical: "Biographical books" },
// Object { Romance: "Romance books" }
//]

Alternatively, instead of using map, you can utilize Object.keys to extract an array from the object that can then be iterated over using map.

Object.keys(json).map(function(key, index) {
//your code here
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nuxt middleware's redirect function is causing the state to become null

My Nuxt app has a middleware issue where everything works fine except when the redirect function is used. When I comment out the line with redirect('/admin') it functions properly, even showing state data in the console log. But as soon as I unco ...

When the page is refreshed, the route fails to load the data

My Vue.JS website is quite simple, utilizing VueX and Vue-Router. I have defined two routes: '#/' and '#/account/' These routes are filled with components from .vue files, loaded dynamically upon page load using http-vue-loader (to avo ...

Inconsistent behavior between Vue.JS and Rails-UJS / Jquery-UJS causing issues with Vuex mutations

During a tutorial, I noticed that two of my view mutations (addCard and addList) are working fine, but the third mutation (editCard) is not functioning properly in Vue. When I attempt to edit a card, the changes are saved correctly in Rails but do not upda ...

What is the best method for loading resources from routes such as /page/:id/subpage and more?

The current structure of my app component is as follows: <app-navigation></app-navigation> <router-outlet></router-outlet> with defined routes: const appRoutes: Routes = [ { path: 'items', component: ListComponent }, ...

Guide to Automatically Updating Angular Component When Service Data Changes

I am currently working on an Angular application that features a sidebar component displaying different menu items based on the user's data. The sidebar should only display an option for "Empresas" if the user has not created any company yet. Once a c ...

VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component: ... <v-stepper-step :rules="[()=>isValid(1)]" > MyStep </v-stepper-step> <v-stepper-content> <Mytag ref="MyReference" /> </v-stepper-content> ... methods: { isValid(number){ ...

Issue with setting cookies in Node.js using Express

Recently I made the switch from regular JavaScript to TypeScript for my project. Everything seems to be functioning properly, except for session handling. This is the current setup of my project: Server.ts App.ts /db/mongo/MongoHandler.ts and some other ...

Is Vuejs a suitable approach for incorporating services?

After familiarizing myself with the MVC architecture while working with Angular, I have now shifted to Vue.js and attempted to structure models and services similarly to Angular. Is this approach effective or is there a better alternative? This service han ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

The best approach for sending parameters to the parent class in TypeScript for optimal efficiency

What's the optimal solution to this problem? I really appreciate how we can specify attributes in the constructor and TypeScript takes care of handling everything to assign values to the props in JavaScript - like I did with 'department' her ...

Organizing objects into arrays in Node.js

I have an array and I need to concatenate an object after the array. Here is my array: const users = [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ] And here is my object: ...

Transform a standard array of strings into a union string literal in TypeScript

I'm currently developing a module where users can specify a list of "allowable types" to be utilized in other functions. However, I'm encountering challenges implementing this feature effectively with TypeScript: function initializeModule<T ex ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Storing Vue.js components as objects in a database: A step-by-step guide

Is there a way to serialize Vue.js components and store them in a database? For example, I am looking to save components like the HelloWorld component typically found in a fresh Vue installation. Any suggestions on a serialization process or package that ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

Working with floating point numbers in Node.js with a zero decimal place

NodeJS interprets float values with a zero after the decimal point as integers, but this behavior occurs at the language level. For example: 5.0 is considered as 5 by NodeJS. In my work with APIs, it's crucial for me to be able to send float values w ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Customize the form using a custom component in react-hook-form: setting a default value

I have been learning ReactJS + TypeScript for 3 months now. Recently, I have a question about using react-hook-form (v7) to edit a form. I want to integrate my custom component into the form and I managed to do it on my own! Here is a snippet of my form p ...

Tips for utilizing MUI Typography properties in version 5

I'm clear on what needs to be done: obtain the type definition for Typography.variant. However, I'm a bit uncertain on how to actually get these. interface TextProps { variant?: string component?: string onClick?: (event: React.MouseEvent&l ...

Error in Typescript: Using forEach method - 'string' type cannot be assigned to 'never' type

I encountered an issue with this code where it's giving me an error message "Type 'string' is not assignable to type 'never'" at the specified comment. type serviceInfoType = { PORT: number; HOST: string; MS_NAME: strin ...