Vue 3: Bind ref value to object property - node.js

I'm running into an issue where I'm trying to bind an object property to a ref in Vue, using the new composition API. I'm expecting the template to re-render with the new value after setting the ref value, but I'm however getting a RefImpl {} instead. How would I solve this?
<template>
<v-card>
<v-card-text class="pa-2">
<div v-for="(social, index) in socials" :key="index">
<p>{{ social.value }}</p>
</div>
</v-card-text>
</v-card>
</template>
<script>
import { onMounted, ref } from "#vue/composition-api/dist/vue-composition-api";
export default {
setup() {
const testVariable = ref(0);
const socials = [
{
value: testVariable,
}
];
onMounted(() => {
setTimeout(() => testVariable.value = 100, 1000);
});
return {
socials,
}
},
}
</script>
<style scoped></style>

Your socials variable does not unref inner refs in template. Basically what you have to do in your template is using social.value.value. So I think renaming that variable would be better to something like
const socials = [
{
variable: testVariable,
}
];
So that you could do social.variable.value.
Details from Vue docs:
Note the unwrapping only applies to top-level properties - nested access to refs will not be unwrapped: Read More

Looks like your code works:
const { onMounted, ref } = Vue
const app = Vue.createApp({
setup() {
const testVariable = ref(0);
const socials = [{ value: testVariable, }];
onMounted(() => {
setTimeout(() => testVariable.value = 100, 1000);
});
return { socials, }
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3.2.29/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="(social, index) in socials" :key="index">
<p>{{ social.value }}</p>
</div>
</div>

Related

Is there a way to reference the images in vue?

I'm building a SPA using vue.js, I need to assign a div background-image referencing something in the following path:
I'm trying to reference src/assets/img/firstCard.jpg but for some reason it doesn't shows the image, this is how I'm binding the image:
HTML:
<a class="card">
<div
class="card__background"
v-bind:style="secondCard">
</div>
<div class="card__content">
<p class="card__category">Gratuita</p>
<h3 class="card__heading">Ademas en diferentes plataformas.</h3>
</div>
</a>
JS:
<script>
export default {
data () {
return {
thirdCard: {
'background-image': require('#/assets/img/firstCard.jpg')
},
secondCard: {
'background-image': require('#/assets/img/firstCard.jpg')
},
firstard: {
'background-image': require('#/assets/img/firstCard.jpg')
}
}
}
}
</script>
Thank you all for your time.
You can try to make method or computed property:
getUrl (img) {
return require(`#/assets/img/${img}.jpg`);
}
then call that method in data object (for background-image you need to specify url):
data () {
return {
firstCard: {
'background-image': `url(${this.getUrl('firstCard')})`
}
}
},

React - trying to save fetched data in a variable but the variable returns empty

I fetched json data with async await and i wanted to save the fetched data in a variable in order to be able to use it with a map in my component,
the data comes in properly inside the function - i checked with an alert , and also in the variable inside the function it does display all the data , but somehow the variable outside the function returns empty .
here is some code:
both alerts in the following code return the right data.
export let fetchPosts = [];
export async function FetchPosts() {
await axios.get('https://jsonplaceholder.typicode.com/posts').then(
res => {
alert(JSON.stringify(res.data))
fetchPosts = JSON.stringify(res.data);
alert(fetchPosts)
}
).catch(err => {
alert('err');
})
}
import { fetchPosts } from '../services/post';
import { FetchPosts } from '../services/post';
export default function Posts() {
function clickme() {
FetchPosts()
}
return (<>
<button onClick={clickme}>Click me</button>
{fetchPosts.map((post, index) => (
<div key={post.id} className="card" style={{ 'width': '16rem', 'display': 'inline-block', 'margin': '5px' }}>
<div className="card-body">
<h6 className="title">{post.title}</h6>
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</>)
}
State is the issue
React doesn't automatically reload on your singleton fetchPosts.
Instead, try...
export function FetchPosts() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
then
import { useState } from 'react';
import { FetchPosts } from '../services/post';
export default function Posts() {
const [posts, setPosts] = useState([]);
function clickme() {
FetchPosts().then(res => {
setPosts(res.data);
});
}
return (<>
<button onClick={clickme}>Click me</button>
{posts.map((post, index) => (
<div key={post.id} className="card" style={{ width: '16rem', display: 'inline-block', margin: '5px' }}>
<div className="card-body">
<h6 className="title">{post.title}</h6>
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</>)
}
https://codesandbox.io/s/jolly-almeida-q4331?fontsize=14&hidenavigation=1&theme=dark
If you want global state, that's another topic you should dive into entirely but you can do it with a singleton, you just need to incorporate it with hooks and an event emitter. I have a bit of a hacked version of this here https://codesandbox.io/s/react-typescript-playground-forked-h8rpu but you should probably stick to redux or mobx or AppContext which is more of a popular pattern.

React how to pass state without rendering component

I have an issue where when I start at the root and click through the links all the states load in fine but when I got to copy and paste the URL into a new window it doesnt show, would I be right to assume its because the previous component isnt being rendered to set the state?
Hopefully someone can point me to some helpful articles or even have experienced this before?
Here is a link to a screen recording I made to better show what I mean https://youtu.be/M0390D4oJDg
CODE
import React from "react";
import { useLocation, useParams } from "react-router";
import PostBlock from "./PostBlock";
const PostList = () => {
const {thread} = useParams()
const { state: { description, title } = {} } = useLocation();
return (
<div>
<div className="m-10 flex justify-center">
<div style={{ width: "1216px" }}>
<div className="flex justify-center">
<div className="flex-1 justify-center mb-5 p-5 h-64 border border-gray-300">
<div>{title}</div>
<div>{description}</div>
</div>
</div>
<table className="min-w-full table-auto">
<thead className="justify-between">
<tr className="bg-gray-800">
<th className="px-8 py-2 text-left text-white">Posts</th>
</tr>
</thead>
<tbody className="bg-gray-200">
<PostBlock thread={thread}/>
</tbody>
</table>
</div>
</div>
</div>
);
};
export default PostList;
LINK
<Link to={{ pathname: `/thread/${thread}`, state: {title: title, description: description} }}>
URL
http://localhost:3000/thread/jxvgOKPrSiCnI2ocDxgJ
This react stuff is harder than I initially thought
Don't give up easily. It's one of the beautiful things!
Start with optional chaining.
const title = useLocation()?.state?.title;
const description = useLocation()?.state?.description;
If this is not supported, use &&:
const title = useLocation() && useLocation().state && useLocation().state.title;
const description = useLocation() && useLocation().state && useLocation().state.description;
And only when title and description is not null, render your contents.
const PostList = () => {
const { thread } = useParams();
const title = useLocation() && useLocation().state && useLocation().state.title;
const description = useLocation() && useLocation().state && useLocation().state.description;
return title && description ? <div></div> : null;
};
Now the code will not render the content until and unless both the values are set. And this will make sure your code loads without any errors.
I am a bit confused as to what your question really is, but you've got some issues with your code. Try this:
const PostList = () => {
const { thread } = useParams();
const { state: { description, title } = {} } = useLocation();
return <div></div>;
};
There is no reason to initialize useLocation() twice. You could've also initialized it into one constant and then access description and state through it.
const PostList = () => {
const { thread } = useParams();
const location = useLocation();
console.log(location.state.title, location.state.description);
return <div></div>;
};
Additionally, you can incorporate object?.property method as a failsafe if your state is empty:
console.log(location?.state?.title);
Take a look at proper useLocation usage here

how can injection dynamic html element to page with next.js?

how can dynamic injection html element to page with next.js? that these elements Unknown type like(input, checkbox, img,...). this element specified with api that return json type like this:
[{
"id":"rooms",
"title":"Rooms",
"order":1,
"type":"string",
"widget":"select",
"data":[{
"Id":18,
"ParentId":null,
"Title":"One",
"Level":null,
"Childrens":[]
},
{"Id":19,
"ParentId":null,
"Title":"Two",
"Level":null,
"Childrens":[]
},
{"Id":20,
"ParentId":null,
"Title":"Three",
"Level":null,
"Childrens":[]
}]
},
{
"id":"exchange",
"title":"Exchange",
"order":0,
"type":"boolean",
"widget":"checkbox",
"data":[]
}]
my try is:
Index.getInitialProps = async function({req, query}) {
const res= await fetch('url api')
var elements= await res.json()
var test = () => (
<div>
{...... convert json to html elements.......}
</div>
)
return {
test
}
})
function Index(props) {
return(
<a>
{props.test}
</a>
)
}
result is null, mean nothing for presentation.
the question is, Do I do the right thing? Is there a better way?
What happens is that during the transfer of props from server to client in getInitialprops, JSON is serialized and so functions are not really serialized. See https://github.com/zeit/next.js/issues/3536
Your best bet is to convert the test data into a string of HTML data and inject it using dangerouslySetInnerHTML. An example will be:
class TestComponent extends React.Component {
static async getInitialProps() {
const text = '<div class="homepsage">This is the homepage data</div>';
return { text };
}
render() {
return (
<div>
<div className="text-container" dangerouslySetInnerHTML={{ __html: this.props.text }} />
<h1>Hello world</div>
</div>
);
}
}
The catch with this is that the string you return must be a valid HTML (not JSX). So notice I used class instead of className
You can read more about it here: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Angularjs jQuery FIle Upload

I'm new at Angularjs and I'm trying to create an AngularJS project with jQuery File Upload but I could not distinguish between directives file controllers file and the view.
Can anyone help me by providing me a clear structure of how files should be placed? (controllers, directives, and view)
I wrote something for my very first Angular.js project. It's from before there was an Angular.js example, but if you want to see the hard way, you can have it. It's not the best, but it may be a good place for you to start. This is my directives.js file.
(function(angular){
'use strict';
var directives = angular.module('appName.directives', []);
directives.directive('imageUploader', [
function imageUploader() {
return {
restrict: 'A',
link : function(scope, elem, attr, ctrl) {
var $imgDiv = $('.uploaded-image')
, $elem
, $status = elem.next('.progress')
, $progressBar = $status.find('.bar')
, config = {
dataType : 'json',
start : function(e) {
$elem = $(e.target);
$elem.hide();
$status.removeClass('hide');
$progressBar.text('Uploading...');
},
done : function(e, data) {
var url = data.result.url;
$('<img />').attr('src', url).appendTo($imgDiv.removeClass('hide'));
scope.$apply(function() {
scope.pick.photo = url;
})
console.log(scope);
console.log($status);
$status.removeClass('progress-striped progress-warning active').addClass('progress-success');
$progressBar.text('Done');
},
progress : function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$progressBar.css('width', progress + '%');
if (progress === 100) {
$status.addClass('progress-warning');
$progressBar.text('Processing...');
}
},
error : function(resp, er, msg) {
$elem.show();
$status.removeClass('active progress-warning progress-striped').addClass('progress-danger');
$progressBar.css('width', '100%');
if (resp.status === 415) {
$progressBar.text(msg);
} else {
$progressBar.text('There was an error. Please try again.');
}
}
};
elem.fileupload(config);
}
}
}
]);
})(window.angular)
I didn't do anything special for the controller. The only part of the view that matters is this:
<div class="control-group" data-ng-class="{ 'error' : errors.image }">
<label class="control-label">Upload Picture</label>
<div class="controls">
<input type="file" name="files[]" data-url="/uploader" image-uploader>
<div class="progress progress-striped active hide">
<div class="bar"></div>
</div>
<div class="uploaded-image hide"></div>
</div>
</div>

Resources