Data is not fetching properly in SSG Next.js - next.js

While creating the post (for the blog) using Jodit Editor, I used to directly save it's output (html string) into mongo.
Then after adding SSG, at the build time, the (consoled) fetched data appears as this.
Whereas simply fetching the api shows data correctly. here
Code of getStaticProps & getStaticPaths
export async function getStaticProps({ params }) {
try {
const { data } = await axios.post(baseUrl + getPostBySlug, { slug: params?.slug });
console.log({ slug: params?.slug }, 'data 2 ->', data); // here is the data consoled
return {
props: { post: data?.data ?? null },
revalidate: 10,
}
}
catch (err) {
return {
props: { post: null },
revalidate: 10,
}
}
}
export async function getStaticPaths() {
try {
const res = await fetch(baseUrl + getAllPosts, { method: 'GET' });
const data = await res?.json();
if (data?.success && data?.data) {
return {
paths: data?.data?.map(({ slug }) => ({ params: { slug } })),
fallback: true,
}
}
else {
return {
paths: [{ params: { slug: '/' } }],
fallback: true,
}
}
}
catch (err) {
return {
paths: [{ params: { slug: '/' } }],
fallback: true,
}
}
}
Final output, a SSG page but with no data init -> here

You need to update to Axios ^1.2.1 - there was an issue with previous versions.
You can set the headers as a temporary solution to prevent this from happening.
await axios.post("your/api/url",{
headers: { Accept: 'application/json', 'Accept-Encoding': 'identity' },
{ slug: "url-slug" }
)

Related

How to mutation store state in build query redux toolkit

Created an initialState and will be updated the totalPage and currentPage after got the users list.
I found out onQueryStarted from docs, it able to update the store state in this method but only look like only for builder.mutation.
what's the correct way to get the user list and update the store page value in redux toolkit?
Listing two part of the code below:
apiSlice
component to use the hook
// 1. apiSlice
const usersAdapter = createEntityAdapter({})
export const initialState = usersAdapter.getInitialState({
totalPage: 0,
currentPage: 0,
})
export const usersApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
getUsers: builder.query({ // <--- the docs are using builder.mutation, but i needed to pass params
query: (args) => {
const { page, limit } = args;
return {
url: `/api/users`,
method: "GET",
params: { page, limit },
}
},
validateStatus: (response, result) => {
return response.status === 200 && !result.isError
},
transformResponse: (responseData) => { // <<-- return { totalPages: 10, currentPage: 1, users: [{}] }
const loadedUsers = responseData?.users.map((user) => user)
return usersAdapter.setAll(initialState, loadedUsers)
},
async onQueryStarted(arg, { dispatch, queryFulfilled }) {
try {
const { data } = await queryFulfilled
const {totalPages, currentPage} = data; <----- totalPages & currentPage values are still 0 as initialState
dispatch(setPages({ currentPage, totalPages }))
} catch (error) {
console.error("User Error: ", error)
}
},
providesTags: (result, error, arg) => {
if (result?.ids) {
return [
{ type: "User", id: "LIST" },
...result.ids.map((id) => ({ type: "User", id })),
]
} else return [{ type: "User", id: "LIST" }]
},
})
})
});
export const {
useGetUsersQuery,
} = usersApiSlice
component to use the hook
Try to use the hook in user landing page
const UsersList = () => {
const { data: users, isLoading, isSuccess, isError } = useGetUsersQuery({page: 1, limit: 10 })
return (
<div>return the users data</div>
)
}
update the store value after get the data return

Getting the categoryId of a post in Graphql

This is my Graphql query for getting posts from headless wordpress:
export const GET_POSTS = gql`
query GET_POSTS( $uri: String, $perPage: Int, $offset: Int, $categoryId: Int ) {
posts: posts(where: { categoryId: $categoryId, offsetPagination: { size: $perPage, offset: $offset }}) {
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
...ImageFragment
}
}
categories {
edges {
node {
categoryId
name
}
}
}
}
}
pageInfo {
offsetPagination {
total
}
}
}
}
${ImageFragment}
`;
When i do this: console.log("DATAAAA", data.posts.edges);
i get:
DATAAAA [
{
node: {
id: 'cG9zdDo0MA==',
title: 'postttt',
excerpt: '<p>dlkfjdsflkdslkdjfkldsf</p>\n',
slug: 'postttt',
featuredImage: null,
categories: [Object],
__typename: 'Post'
},
__typename: 'RootQueryToPostConnectionEdge'
},
{
node: {
id: 'cG9zdDox',
title: 'Hello world!',
excerpt: '<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n',
slug: 'hello-world',
featuredImage: null,
categories: [Object],
__typename: 'Post'
},
__typename: 'RootQueryToPostConnectionEdge'
}
]
But when try to go further, inside node, like this: console.log("DATAAAA", data.posts.edges.node); in order to get the categoryId which is inside categories: [Object], i get undefined.
How to get categoryId based on this query?
What i want to do is to get only the posts by a given category in getStaticProps like this, but i dont know how to get that categoryId dynamically. This is what my getStaticProps function looks like:
export async function getStaticProps(context) {
console.log("THE CONTEXT", context);
const { data, errors } = await client.query({
query: GET_POSTS,
variables: {
uri: context.params?.slug ?? "/",
perPage: PER_PAGE_FIRST,
offset: null,
categoryId: <===== How to get this dynamically?
},
});
const defaultProps = {
props: {
data: data || {},
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
This is my getStaticPaths function:
export async function getStaticPaths() {
const { data } = await client.query({
query: GET_CATEGORY_SLUGS_ID,
});
const pathsData = [];
data?.categories?.edges.node &&
data?.categories?.edges.node.map((category) => {
if (!isEmpty(category?.slug)) {
pathsData.push({ params: { slug: category?.slug } });
}
});
return {
paths: pathsData,
fallback: FALLBACK,
};
}
and this is what i get from context console.log("THE CONTEXT", context);:
THE CONTEXT {
params: { slug: 'uncategorized' },
locales: undefined,
locale: undefined,
defaultLocale: undefined
}
Any help would be appreciated.

Redirect function in Nuxt middleware is making state null

I have a Nuxt app in which everything works fine in middleware except when I use redirect.
When I comment the redirect('/admin') line it works fine even the state data is present when console logged. As soon as I uncomment the redirect line it makes the state null.
Please help if someone knows this issue. This exact code works in my other projects but not here.
This is my auth.js file in the middleware folder.
export default function ({ store, route, redirect }) {
const user = store.getters['user/user']
const blockRouteAdmin = /\/admin\/*/g
const blockRouteManager = /\/manager\/*/g
const path = ['/signup', '/login']
let value = path.includes(route.path)
if (user) {
if (user.isAdmin) {
if (!route.path.match(blockRouteAdmin)) {
redirect('/admin')
}
}
if (user.isManager) {
if (!route.path.match(blockRouteManager)) {
redirect('/manager')
}
}
if (user.isUser) {
if (
route.path.match(blockRouteAdmin) ||
route.path.match(blockRouteManager) ||
value
) {
console.log('isUser', user.isUser)
redirect('/')
}
}
}
if (!user) {
if (
route.path.match(blockRouteAdmin) ||
route.path.match(blockRouteManager)
) {
redirect('/')
} else {
redirect()
}
}
}
Here is my nuxt.config.js
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'aitl',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/firebaseConfig.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/buefy
'nuxt-buefy',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
// https://go.nuxtjs.dev/content
'#nuxt/content',
],
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en',
},
},
// Content module configuration: https://go.nuxtjs.dev/config-content
content: {},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
}
My index.js inside store.
import { vuexfireMutations } from 'vuexfire'
import { getUserFromCookie } from '../helper/index.js'
export const mutations = {
...vuexfireMutations,
}
export const actions = {
async nuxtServerInit({ dispatch, commit }, { req }) {
try {
const user = getUserFromCookie(req)
if (user) {
await dispatch('user/setUSER', {
email: user.email,
isAdmin: user.admin,
isManager: user.manager,
isUser: user.user,
uid: user.user_id,
name: user.name,
})
}
} catch (err) {
console.log(err)
}
},
}
User.js in store folder
import { auth } from '../plugins/firebaseConfig'
import Cookies from 'js-cookie'
export const state = () => ({
user: null,
})
export const getters = {
user(state) {
return state.user
},
}
export const actions = {
async userlogin({ dispatch }, user) {
try {
const token = await auth.currentUser.getIdToken(true)
const userInfo = {
email: user.email,
isAdmin: user.admin,
isManager: user.manager,
isUser: user.user,
uid: user.uid,
name: user.displayName,
}
Cookies.set('access_token', token)
await dispatch('setUSER', userInfo)
} catch (err) {
console.log(err)
}
},
setUSER({ commit }, user) {
commit('setUSER', user)
},
}
export const mutations = {
setUSER(state, user) {
state.user = user
},
}
The issue was solved by going from target: 'static' to target: 'server', aka mirroring the settings of another working project.

img not loading from :src

I am getting the image location from firestore and would like to show the image using v-bind:src. You can find my code below:
<b-avatar v-bind:src = "profilepic" class="mr-5" size="8em"></b-avatar>
my methods can be found below:
export default {
data() {
return {
uid: "",
profilepic: "",
}
},
methods: {
getprofilepic() {
fb.storage().ref('users/' + this.uid + '/profile.jpg').getDownloadURL().then(imgURL => {
this.profilepic = imgURL;
alert(this.profilepic); // shows the correct path
})
},
}
created() {
this.uid = fb.auth().currentUser.uid;
this.getprofilepic();
}
}
I am confident that this.profilepic is storing the correct path as if i were to manually type in the path, it will show. I am suspecting that the page loaded before path could be retrieve from firestore. How can i work around this? Thank you in advance.
I have tried hardcoding the path directly to the data and it works fine. The code can be found below:
data() {
return {
uid: "",
profilepic: "*my firebase storage path*",
}
},
With that im not really sure why isnt it still showing
In the script below the template tags, you need to make sure to include the image, and of course, instead of putting my path, put your image's path!
<script>
export default {
data() {
return {
files: {
my_pic: require('/src/assets/img/avatars/logo.png')
}
};
},
}
};
</script>
Then in your and where you want to put your image, you need to put it in this format
<img :src="files.my_pic">
Let me know if this helps or if you want me to expand more.
Try waiting for the uuid to get retrieved:
<template>
<img height="200" v-bind:src = "profilepic" />
</template>
<script>
export default {
data() {
return {
uuid: undefined,
profilepic: undefined
}
},
methods: {
getprofilepic() {
fb.storage().ref('users/' + this.uid + '/profile.jpg').getDownloadURL()
.then(imgURL => {
this.profilepic = imgURL;
})
},
getuuid(){
return new Promise((resolve, reject) => {
var user = fb.auth().currentUser;
if(user == null) reject()
if (user) resolve(user.uid)
})
}
},
created() {
this.getuuid()
.then(uuid => this.uuid = uuid)
.then(() => {
this.getprofilepic();
})
}
};
</script>
As you can see in this example, it does not matter how long it takes for the URL to load: Vue SFC Playground
When Vue Loader compiles the <template> blocks in SFCs, it also converts any encountered asset URLs into webpack module requests.
For example, the following template snippet:
<img src="../image.png">
will be compiled into:
createElement('img', {
attrs: {
src: require('../image.png') // this is now a module request
}
})
By default the following tag/attribute combinations are transformed, and can be configured using the transformAssetUrls option.
{
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: ['xlink:href', 'href'],
use: ['xlink:href', 'href']
}
Step 1: Create vue.config.js
module.exports = {
productionSourceMap: false,
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options['transformAssetUrls'] = {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href',
'b-avatar': 'src',
'b-img': 'src',
'b-img-lazy': ['src', 'blank-src'],
'b-card': 'img-src',
'b-card-img': 'src',
'b-card-img-lazy': ['src', 'blank-src'],
'b-carousel-slide': 'img-src',
'b-embed': 'src'
}
return options
})
}
}
Step 2: Inside main.js import vue.config
import '../vue.config'
Step 3: Create your html template
<template>
<b-avatar :src="profilepic" class="mr-5" size="8em"></b-avatar>
</template>
<script>
import { BAvatar } from 'bootstrap-vue'
export default {
name: 'bootstrap-image-avatar',
components: {
'b-avatar': BAvatar
},
data() {
return {
uid: "",
profilepic: "",
}
},
methods: {
getprofilepic() {
fb.storage().ref('users/' + this.uid + '/profile.jpg').getDownloadURL().then(imgURL => {
this.profilepic = imgURL;
alert(this.profilepic); // shows the correct path
})
},
}
created() {
this.uid = fb.auth().currentUser.uid;
this.getprofilepic();
}
}
</script>

How to test cyclejs http driver?

Suppose I have an API that return user detail:
/api/get_user/1
{
"status": 200,
"data": {
"username": "username1",
"email": "username#email.com"
}
}
And a "main function" like this:
function main (sources) {
const request$ = sources.ACTIONS
.filter(action => action.type === 'GET_USER_REQUEST')
.map(action => action.payload)
.map(payload => ({
category: 'GET_USER_REQUEST',
url: `${BASE_URL}/api/get_user/${payload.userId}`,
method: 'GET'
}))
const action$ = sources.HTTP
.select('GET_USER_REQUEST')
.flatten()
.map(response => response.data)
const sinks = {
HTTP: request$,
LOG: action$
}
return sinks
}
For testing the "ACTION" source, I can simply made an xstream observable
test.cb('Test main function', t => {
const actionStream$ = xs.of({
type: 'GET_USER_REQUEST',
payload: { userId: 1 }
})
const sources = { ACTION: actionStream$ }
const expectedResult = {
category: 'GET_USER_REQUEST',
url: `${BASE_URL}/api/get_user/${payload.userId}`,
method: 'GET'
}
main(sources).HTTP.addEventListener({
next: (data) => {
t.deepEqual(data, expectedResult)
},
error: (error) => {
t.fail(error)
},
complete: () => {
t.end()
}
})
})
The question is. Is it possible to do the same thing (using plan xstream observable)
to test cycle-http driver without a helper from something like nock?
Or is there a better way to test something like this?
You can mock out the HTTP source like so:
test.cb('Test main function', t => {
const actionStream$ = xs.of({
type: 'GET_USER_REQUEST',
payload: { userId: 1 }
})
const response$ = xs.of({
data: {
status: 200,
data: {
username: "username1",
email: "username#email.com"
}
}
});
const HTTP = {
select (category) {
// if you have multiple categories you could return different streams depending on the category
return xs.of(response$);
}
}
const sources = { ACTION: actionStream$, HTTP }
const expectedResult = {
category: 'GET_USER_REQUEST',
url: `${BASE_URL}/api/get_user/${payload.userId}`,
method: 'GET'
}
main(sources).HTTP.addEventListener({
next: (data) => {
t.deepEqual(data, expectedResult)
},
error: (error) => {
t.fail(error)
},
complete: () => {
t.end()
}
})
})
Really, we should have a mockHTTPSource helper to make this a bit easier. I have opened an issue to that effect. https://github.com/cyclejs/cyclejs/issues/567
If you want to test that certain things happen at the correct time, you could use this pattern in conjunction with #cycle/time.
http://github.com/cyclejs/time

Resources